我已经使用SpriteKit构建了一款游戏,除了让用户输入他们的名字来存储他们的高分之外,我已经完全使用了它。我使用NSUserDefaults将分数存储为前5个分数的数组。我也想存储他们的名字,因为我最终计划将存储移动到服务器而不是NSUserDefaults,以便让玩家获得高分。Swift iOS:我如何在SpriteKit中获得玩家的名字?
我的想法是在游戏首次在设备上运行时提供一个UIAlertController,通过文本输入字段获取它们的名称,然后将其存储在NSUserDefaults中。但无论我在哪里放置UIAlertController(GameScene.swift,GameViewController.swift,甚至是AppDelegate.swift)的代码,它都不会弹出。
我使用警报的代码是:
let ac = UIAlertController(title: "Enter Name", message: nil, preferredStyle: .Alert)
ac.addTextFieldWithConfigurationHandler(nil)
ac.addAction(UIAlertAction(title: "OK", style: .Default) { [unowned self, ac] _ in
let playerName = ac.textFields![0]
})
ac.presentViewController(ac, animated: true, completion: nil)
这是基于注释更新的代码如下,包括整个viewDidLoad中功能:
override func viewDidLoad() {
super.viewDidLoad()
let ac = UIAlertController(title: "Enter Name", message: nil, preferredStyle: .Alert)
ac.addTextFieldWithConfigurationHandler(nil)
ac.addAction(UIAlertAction(title: "OK", style: .Default) { [unowned self, ac] _ in
let playerName = ac.textFields![0]
})
self.presentViewController(ac, animated: true, completion: nil)
if let scene = GameScene(fileNamed:"GameScene") {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = false
skView.showsNodeCount = false
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
currentGame = scene
scene.viewController = self
}
}
当我将它更改为self时,它不再崩溃应用程序,但它不显示警报viewcontroller,它给了我这个错误:尝试在上呈现其视图不在窗口层次结构中! –
该错误消息表明当您调用'presentViewController'时,GameViewController不显示在屏幕上。你的'GameViewController'类中的代码是从哪里调用的? – Deyton
感谢您的帮助!我已经在场景创建之前和之后尝试过它。我会在另一条评论中发布代码,因为它不会让我在这里发布。 –