B_s B_s - 6 months ago 416
Swift Question

Swift alert view (iOS8) with OK and cancel button, which button tapped

I have an alert view in Xcode written in Swift and I'd like to determine which button the user selected (it is a confirmation dialog) to do nothing or to execute something.
Currently I have:

@IBAction func pushedRefresh(sender: AnyObject) {
var refreshAlert = UIAlertView()
refreshAlert.title = "Refresh?"
refreshAlert.message = "All data will be lost."
refreshAlert.addButtonWithTitle("Cancel")
refreshAlert.addButtonWithTitle("OK")
refreshAlert.show()
}


I'm probably using the buttons wrong, please do correct me since this is all new for me.

Thank you!

Answer

If you are using iOS8, you should be using UIAlertController instead for UIAlertView is deprecated:

https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIAlertController_class/

Here is an example of how to use it:

var refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.Alert)

refreshAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
  print("Handle Ok logic here")
  }))

refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { (action: UIAlertAction!) in
  print("Handle Cancel Logic here")
  }))

presentViewController(refreshAlert, animated: true, completion: nil)

As you can see the block handlers for the UIAlertAction handle the button presses. A great tutorial is here (although this tutorial is not written using swift): http://hayageek.com/uialertcontroller-example-ios/