如何在UIAlertController中调用文本字段?

时间:2015-03-11 18:30:45

标签: swift uialertcontroller

所以,我正在创建一个应用程序,当按下“开始”按钮时,会弹出一个警告UIAlertController,并且有两个文本字段询问玩家的名字,我将把玩家名称移动到游戏的屏幕(这是一个Tic-Tac-Toe应用程序)通过

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)

所以我现在的问题是如何将用户输入的值输入到我的GameScreen的TextFieldWithConfigurationHandler。我UIAlertController的代码如下:

@IBAction func startButton(sender: AnyObject)
    {
        var playerNameEntry = UIAlertController(title: "Player names", message: nil, preferredStyle: .Alert)

        playerNameEntry.addTextFieldWithConfigurationHandler({textfield in textfield.placeholder = "Player 1"})

        playerNameEntry.addTextFieldWithConfigurationHandler({textfield in textfield.placeholder = "Player 2"})

        var continueButton = UIAlertAction(title: "Continue", style: .Default, { action in

            self.performSegueWithIdentifier("gameSegue", sender: nil)

        })

        playerNameEntry.addAction(continueButton)

        var cancelButton = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)

        playerNameEntry.addAction(cancelButton)

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

    }

感谢您花时间阅读本文,如果您回答,谢谢十倍

1 个答案:

答案 0 :(得分:1)

continueButton处理程序中,您可以playerNameEntry访问警报控制器。因此,您可以访问其textFields数组:

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIAlertController_class/#//apple_ref/occ/instp/UIAlertController/textFields

因此,您可以访问每个文本字段的text

    var continueButton = UIAlertAction(title: "Continue", style: .Default, { action in
        // code goes here
        let tfs = playerNameEntry.textFields as [UITextField]
        // ...do stuff with the `text` of each text field...
        self.performSegueWithIdentifier("gameSegue", sender: nil)
    })