我使用 SpriteKit 构建了一个游戏,除了让用户输入他们的名字来存储他们的高分外,我的游戏功能齐全。我正在使用 NSUserDefaults 将分数存储为前 5 名分数的数组。我也想存储他们的名字,因为最终我计划将存储移动到服务器而不是 NSUserDefaults 以允许玩家竞争高分。
我的想法是当游戏首次在设备上运行时显示一个 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
}
}
最佳答案
呈现 View Controller 通常不会在 viewDidLoad
内部工作,因为它是在 View 加载到内存之后但在屏幕上呈现之前调用的(请参阅 View Controller 生命周期 here ) .您可以在那里设置东西(比如您的场景),但任何动画或交互元素必须稍后完成。
放置它的更安全的地方是 viewDidAppear
(以及一些逻辑以确保它不会重复出现)或响应按钮上的点击。
此外,您必须从屏幕上已有的 View Controller 调用 presentViewController
才能显示它。所以,如果您的 GameViewController
中有这段代码,您可以更改
ac.presentViewController(ac, animated: true, completion: nil)
到
self.presentViewController(ac, animated: true, completion: nil)
关于ios - swift iOS : How can I get player's name in SpriteKit?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38962836/