How to add action to UIAlertView in Swift (iOS 7)
I tested your code and it is working fine for me it prints the respective result:
func showAlert(){ var createAccountErrorAlert: UIAlertView = UIAlertView() createAccountErrorAlert.delegate = self createAccountErrorAlert.title = "Oops" createAccountErrorAlert.message = "Could not create account!" createAccountErrorAlert.addButtonWithTitle("Dismiss") createAccountErrorAlert.addButtonWithTitle("Retry") createAccountErrorAlert.show()}func alertView(View: UIAlertView!, clickedButtonAtIndex buttonIndex: Int){ switch buttonIndex{ case 1: NSLog("Retry"); break; case 0: NSLog("Dismiss"); break; default: NSLog("Default"); break; //Some code here.. }}
It print dismiss when i click on dismiss button.
That's because the index of your retry button is 1, not 0. The dismiss button has index 0.
If you put the following code in a playground, you will actually see the indexes of the buttons (as documented on the addButtonWithTitle method):
var createAccountErrorAlert: UIAlertView = UIAlertView()createAccountErrorAlert.title = "Oops"createAccountErrorAlert.message = "Could not create account!"createAccountErrorAlert.addButtonWithTitle("Dismiss") //Prints 0createAccountErrorAlert.addButtonWithTitle("Retry") //Prints 1
Index is wrong. The following (based on iOS single view default app template) works for me (where I wired a button to trigger @IBAction buttonPressed
). Don't forget to make your view controller a UIAlertViewDelegate
(though the following works without doing so):
import UIKitclass ViewController: UIViewController, UIAlertViewDelegate { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func buttonPressed(sender : AnyObject) { var createAccountErrorAlert: UIAlertView = UIAlertView() createAccountErrorAlert.delegate = self createAccountErrorAlert.title = "Oops" createAccountErrorAlert.message = "Could not create account!" createAccountErrorAlert.addButtonWithTitle("Dismiss") createAccountErrorAlert.addButtonWithTitle("Retry") createAccountErrorAlert.show() } func alertView(View: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) { switch buttonIndex { default: println("alertView \(buttonIndex) clicked") } }}