How to add action to buttons in Alert in Swift

user3806731 picture user3806731 · Jul 5, 2014 · Viewed 16.2k times · Source

I am beginner level programmer. I am trying to add action to buttons on Alert, but it doesn't work. I just want to test if the alert button choice can change the text in label, but it doesn't work. Of course I can see the alert and buttons well, but nothing happens after clicking the button.

@IBOutlet var statusLabelAlert : UILabel

var alertTest = UIAlertView()

@IBAction func alertButton(sender : AnyObject) {

    alertTest.message = "Select one!"
    alertTest.addButtonWithTitle("1st")
    alertTest.addButtonWithTitle("2nd")
    alertTest.addButtonWithTitle("3rd")
    alertTest.title = "Test Alert"
    alertTest.show()

}
func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int){
    switch buttonIndex{
    case 0:
        statusLabelAlert.text = "1st"
    case 1:
        statusLabelAlert.text = "2nd"
    case 2:
        statusLabelAlert.text = "3rd"
    default:
        statusLabelAlert.text = "error"
    }

}

Answer

Mayank Jain picture Mayank Jain · Jul 5, 2014

Is your clickedButtonAtIndex method calling? Put a breakpoint and debug the code. You doesn't set the delegate of alertView.

@IBOutlet var statusLabelAlert : UILabel

var alertTest = UIAlertView()
alertTest.delegate = self   //set the delegate of alertView

@IBAction func alertButton(sender : AnyObject) {

alertTest.message = "Select one!"
alertTest.addButtonWithTitle("1st")
alertTest.addButtonWithTitle("2nd")
alertTest.addButtonWithTitle("3rd")
alertTest.title = "Test Alert"
alertTest.show()

}
func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int){
switch buttonIndex{
case 0:
    statusLabelAlert.text = "1st"
case 1:
    statusLabelAlert.text = "2nd"
case 2:
    statusLabelAlert.text = "3rd"
default:
    statusLabelAlert.text = "error"
}

}