Swift iOS: 如何在 SpriteKit 中获取玩家的名字?

Swift iOS: How can I get player's name in SpriteKit?

我已经使用 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
    }

}
//1. Create the alert controller.            
var alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .Alert)

//2. Add the text field. You can configure it however you need.
alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in
    textField.text = "Some default text."
})

//3. Grab the value from the text field, and print it when the user clicks OK. 
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in
    let textField = alert.textFields![0] as UITextField
    println("Text field: \(textField.text)")
}))

// 4. Present the alert.
self.presentViewController(alert, animated: true, completion: nil)

is that's what you except? 

呈现视图控制器通常不会在 viewDidLoad 内部工作,因为它是在视图加载到内存之后但在屏幕上呈现之前调用的(请参阅视图控制器生命周期 here).你可以在那里设置东西(比如你的场景)但是任何动画或交互元素必须稍后完成。

放置它的更安全的地方是 viewDidAppear(以及一些逻辑以确保它不会重复出现)或响应点击按钮。

此外,您必须从屏幕上已有的视图控制器调用 presentViewController 才能显示它。因此,如果您的 GameViewController 中有此代码,您可以更改

ac.presentViewController(ac, animated: true, completion: nil)

self.presentViewController(ac, animated: true, completion: nil)