ldouglas956
ldouglas956

Reputation: 5

How can I make two Alerts with user inputs open one after another when an app opens?

I am trying to make two alerts pop up to enter two player names for an app. I have tried using the AlertController code in the viewDidLoad and the viewDidAppear functions. While one works fine in viewDidAppear, it throws an error when the second is called because it continues running other code.

Ideally, I would like it to pop up and say "Enter Player 1 Name", give the user an opportunity to input a name, then when submit is pressed start execution on the second alert so that it pops up with "Enter Player 2 Name".

Upvotes: 0

Views: 488

Answers (1)

kamwysoc
kamwysoc

Reputation: 6859

You need to implement a handler for UIAlertAction in which you show another alert. Look at this snippet of code :

let firstAlert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
firstAlert.addTextFieldWithConfigurationHandler({
    textField in
    textField.placeholder = "Some input"
})

let secondAlert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
secondAlert.addTextFieldWithConfigurationHandler({
    textField in
    textField.placeholder = "Some input 2"
})

firstAlert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: {
    action in
    print("text from first alert : + \(firstAlert.textFields?[0].text)")
    self.presentViewController(secondAlert, animated :true, completion :nil)
}))

secondAlert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: {
    action in
    print("text from second alert : + \(firstAlert.textFields?[0].text)")
}))


self.presentViewController(firstAlert, animated: true, completion: {
})

You can use this use this lines of code for example in viewDidLoad or viewDidAppear function on first appeared UIViewController.

Hope it help you

Upvotes: 1

Related Questions