47

I want to add another button other than the "OK" button which should just dismiss the alert. I want the other button to call a certain function.

var logInErrorAlert: UIAlertView = UIAlertView()
logInErrorAlert.title = "Ooops"
logInErrorAlert.message = "Unable to log in."
logInErrorAlert.addButtonWithTitle("Ok")

How do I add another button to this alert, and then allow it to call a function once clicks so lets say we want the new button to call:

 retry()
Bryan Chen
  • 45,816
  • 18
  • 112
  • 143
Stephen Fox
  • 14,190
  • 19
  • 48
  • 52

9 Answers9

166

The Swifty way is to use the new UIAlertController and closures:

    // Create the alert controller
    let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert)

    // Create the actions
    let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
        UIAlertAction in
        NSLog("OK Pressed")
    }
    let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
        UIAlertAction in
        NSLog("Cancel Pressed")
    }

    // Add the actions
    alertController.addAction(okAction)
    alertController.addAction(cancelAction)

    // Present the controller
    self.presentViewController(alertController, animated: true, completion: nil)

Swift 3:

    // Create the alert controller
    let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)

    // Create the actions
    let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
        UIAlertAction in
        NSLog("OK Pressed")
    }
    let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) {
        UIAlertAction in
        NSLog("Cancel Pressed")
    }

    // Add the actions
    alertController.addAction(okAction)
    alertController.addAction(cancelAction)

    // Present the controller
    self.present(alertController, animated: true, completion: nil)
Robin Dirksen
  • 3,322
  • 25
  • 40
Jake
  • 1,756
  • 1
  • 12
  • 7
  • 10
    Unfortunately, I am working with iOS 7.1 at the moment and UIAlertController is only available in iOS 8.0 +. So I have to user UIAlertView – Stephen Fox Jun 12 '14 at 23:51
  • 4
    I did it exactly like you but the error does not appear, instead in the log it says "Warning, attempt to present on <_TtC13NSAlert_Swift14ViewController: 0x7c888f50> whose view is not in the window hierarchy!" Any idea what is the problem? – LinusGeffarth Aug 19 '14 at 20:48
  • In my case, alert appears but buttons are not responding the touches. That said, neither "OK Pressed" nor "Cancel Pressed" shows up. – scaryguy Aug 08 '16 at 04:30
17
func showAlertAction(title: String, message: String){
    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
    alert.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: {(action:UIAlertAction!) in
        print("Action")
    }))
    alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.default, handler: nil))
    self.present(alert, animated: true, completion: nil)
}
Manee ios
  • 1,112
  • 11
  • 14
Chetan
  • 881
  • 14
  • 22
7

UIAlertViews use a delegate to communicate with you, the client.

You add a second button, and you create an object to receive the delegate messages from the view:

class LogInErrorDelegate : UIAlertViewDelegate {

    init {}

    // not sure of the prototype of this, you should look it up
    func alertView(view :UIAlertView, clickedButtonAtIndex :Integer) -> Void {
        switch clickedButtonAtIndex {
            case 0: 
               userClickedOK() // er something
            case 1:
               userClickedRetry()
              /* Don't use "retry" as a function name, it's a reserved word */

            default:
               userClickedRetry()
        }
    }

    /* implement rest of the delegate */
}
logInErrorAlert.addButtonWithTitle("Retry")

var myErrorDelegate = LogInErrorDelegate()
logInErrorAlert.delegate = myErrorDelegate
iluvcapra
  • 9,436
  • 2
  • 30
  • 32
6

Swift 5+

let alert = UIAlertController(title: "Cart!", message: "Are you sure want to remove order details?", preferredStyle: .alert)
        // Create the actions
let okAction = UIAlertAction(title: "YES", style: 
    UIAlertAction.Style.default) {
       UIAlertAction in
       print("Yes Pressed")
}
let cancelAction = UIAlertAction(title: "CANCEL", style: 
    UIAlertAction.Style.cancel) {
       UIAlertAction in
       print("Cancel Pressed")
    }
// Add the actions
alert.addAction(okAction)
alert.addAction(cancelAction)

self.present(alert, animated: true, completion: nil)

OR

let alert = UIAlertController(title: "Alert!", message: "Are you sure want to remove your request?", preferredStyle: .alert)
                // Create the actions
        let okAction = UIAlertAction(title: "YES", style: .destructive) {
               _ in
               print("Yes Pressed")
            self.funRemoveRequest(requestID: (self.requestStatusModel?.data?[sender.tag].id)!)
        }
        let cancelAction = UIAlertAction(title: "CANCEL", style: .cancel) {
               _ in
               print("Cancel Pressed")
            }
        // Add the actions
        alert.addAction(okAction)
        alert.addAction(cancelAction)

        self.present(alert, animated: true, completion: nil)
Shakeel Ahmed
  • 5,361
  • 1
  • 43
  • 34
3

Swift 4 Update

        // Create the alert controller
        let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)

        // Create the actions
        let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
            UIAlertAction in
            NSLog("OK Pressed")
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) {
            UIAlertAction in
            NSLog("Cancel Pressed")
        }

        // Add the actions
        alertController.addAction(okAction)
        alertController.addAction(cancelAction)

        // Present the controller
        self.present(alertController, animated: true, completion: nil)
Xcodian Solangi
  • 2,342
  • 5
  • 24
  • 52
2

based on swift:

let alertCtr = UIAlertController(title:"Title", message:"Message", preferredStyle: .Alert)
let Cancel = AlertAction(title:"remove", style: .Default, handler: {(UIAlertAction) -> Void in })
let Remove = UIAlertAction(title:"remove", style: .Destructive, handler:{(UIAlertAction)-> Void 
    inself.colorLabel.hidden = true    
})
alertCtr.addAction(Cancel)
alertCtr.addAction(Remove)

self.presentViewController(alertCtr, animated:true, completion:nil)}
Alex Pelletier
  • 4,933
  • 6
  • 34
  • 58
2

Swift 3.0 Version of Jake's Answer

// Create the alert controller

let alertController = UIAlertController(title: "Alert!", message: "There is no items for the current user", preferredStyle: .alert)

            // Create the actions
            let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
                UIAlertAction in
                NSLog("OK Pressed")
            }
            let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) {
                UIAlertAction in
                NSLog("Cancel Pressed")
            }

            // Add the actions
            alertController.addAction(okAction)
            alertController.addAction(cancelAction)

            // Present the controller
            self.present(alertController, animated: true, completion: nil)
SARATH SASI
  • 1,395
  • 1
  • 15
  • 39
1

See my code:

 @IBAction func foundclicked(sender: AnyObject) {

            if (amountTF.text.isEmpty)
            {
                let alert = UIAlertView(title: "Oops! Empty Field", message: "Please enter the amount", delegate: nil, cancelButtonTitle: "OK")

                alert.show()
            }

            else {

            var alertController = UIAlertController(title: "Confirm Bid Amount", message: "Final Bid Amount : "+amountTF.text , preferredStyle: .Alert)
            var okAction = UIAlertAction(title: "Confirm", style: UIAlertActionStyle.Default) {
                UIAlertAction in

                JHProgressHUD.sharedHUD.loaderColor = UIColor.redColor()
                        JHProgressHUD.sharedHUD.showInView(self.view, withHeader: "Amount registering" , andFooter: "Loading")
                }
            var cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
                UIAlertAction in

                alertController .removeFromParentViewController()
            }
                            alertController.addAction(okAction)
                            alertController.addAction(cancelAction)

                self.presentViewController(alertController, animated: true, completion: nil)

            }

        }
Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Alvin George
  • 14,148
  • 92
  • 64
0

this is for swift 4.2, 5 and 5+

let alert = UIAlertController(title: "ooops!", message: "Unable to login", preferredStyle: .alert)

alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))

self.present(alert, animated: true)
ArSeN
  • 5,133
  • 3
  • 19
  • 26
Al Mustakim
  • 480
  • 4
  • 11