Worldorg
Worldorg

Reputation: 53

Swift, iOS: How to use UIButton to trigger UIAlertController

I want to use an UIButton to trigger a UIAlertController... in Swift

So in this example I have an "Agree" button below some text, and I want the user to click Agree and have a pop-up alert with 2 options confirming/canceling the agreement. How would I go about connecting the UIButton and the UIAlertController. Also if the user cancels, I want the alert to dismiss and remain on the current VC. If the user agrees, I want it to segue to another view controller.

I fairly new to Swift, so if the answer could be detailed that would be extremely appreciated!

Upvotes: 1

Views: 1624

Answers (1)

Woodstock
Woodstock

Reputation: 22926

You need to add an IBAction (Control drag from your UIButton on your XIB/Storyboard, to the viewController implementation to link the button to the method). Inside the method that you link to the action you need to present the viewController, similar to the below:

func showAlert(sender: UIButton!)
{
    var alert = UIAlertController(title: "Title", message: "Some Message", preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: "Agree", style: UIAlertActionStyle.Default, handler: nil))

    self.presentViewController(alert, animated: true, completion: nil) 
}

Upvotes: 1

Related Questions