Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add action to UIAlertView in Swift (iOS 7)

Tags:

ios

swift

I want to add an action to the Retry button, but when the user presses the Retry button nothing happens.

var createAccountErrorAlert: UIAlertView = UIAlertView()

createAccountErrorAlert.delegate = self                

createAccountErrorAlert.title = "Oops"
createAccountErrorAlert.message = "Could not create account!"
createAccountErrorAlert.addButtonWithTitle("Dismiss")
createAccountErrorAlert.addButtonWithTitle("Retry")

createAccountErrorAlert.show()

Function for determining index of button pressed?

func alertView(View: UIAlertView!, clickedButtonAtIndex buttonIndex: Int){

    switch buttonIndex{

    case 1:
        createAccount()

    default:
        //Some code here..

    }
}
like image 222
Stephen Fox Avatar asked Jun 17 '14 19:06

Stephen Fox


People also ask

How do I add an alert in AppDelegate Swift?

@OrkhanAlizade create a ViewController , put your code into the ViewControllers viewDidAppear method, and in your AppDelegate , set that ViewController as the windows rootViewController (and also don't forget to create the window itself). @DánielNagy it works! Thank you! @OrkhanAlizade you are welcome!

How would I create a UIAlertView in Swift?

var alertView = UIAlertView(); alertView.

How do I show a popup message in Swift?

Adding Action Buttons to Alert Dialog To create an action button that the user can tap on, we will need to create a new instance of an UIAlertAction class and add it to our alert object. To add one more button to UIAlertController simply create a new UIAlertAction object and add it to the alert.


1 Answers

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.

like image 124
Saurav Nagpal Avatar answered Oct 24 '22 03:10

Saurav Nagpal