Hytyotwo
Hytyotwo

Reputation: 3

How do I call a textfield from within an UIAlertController?

So, I am making an app where when the "Start" button is pressed, an Alert via UIAlertController pops up and there are two textfields asking for the players' names, where I will move the player names to the game's screen (it's a Tic-Tac-Toe app) via

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

So my question at the moment is how to get the values that the user inputs into the TextFieldWithConfigurationHandler to my GameScreen. My code for the UIAlertController is as follows:

@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)

    }

thanks for taking to time to read this and if you answer, thanks tenfold

Upvotes: 0

Views: 88

Answers (1)

matt
matt

Reputation: 534950

In your continueButton handler, you have access to the alert controller as playerNameEntry. Therefore you can access its textFields array:

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

Therefore you can access the text of each of those text fields.

    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)
    })

Upvotes: 1

Related Questions