[ios] Writing handler for UIAlertAction

I'm presenting a UIAlertView to the user and I can't figure out how to write the handler. This is my attempt:

let alert = UIAlertController(title: "Title",
                            message: "Message",
                     preferredStyle: UIAlertControllerStyle.Alert)

alert.addAction(UIAlertAction(title: "Okay",
                              style: UIAlertActionStyle.Default,
                            handler: {self in println("Foo")})

I get a bunch of issues in Xcode.

The documentation says convenience init(title title: String!, style style: UIAlertActionStyle, handler handler: ((UIAlertAction!) -> Void)!)

The whole blocks/closures is a little over my head at the moment. Any suggestion are much appreciated.

This question is related to ios uialertview swift uialertcontroller

The answer is


  1. In Swift

    let alertController = UIAlertController(title:"Title", message: "Message", preferredStyle:.alert)
    
    let Action = UIAlertAction.init(title: "Ok", style: .default) { (UIAlertAction) in
        // Write Your code Here
    }
    
    alertController.addAction(Action)
    self.present(alertController, animated: true, completion: nil)
    
  2. In Objective C

    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Title" message:@"Message" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *OK = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
    {
    }];
    
    [alertController addAction:OK];
    
    [self presentViewController:alertController animated:YES completion:nil];
    

create alert, tested in xcode 9

let alert = UIAlertController(title: "title", message: "message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: self.finishAlert))
self.present(alert, animated: true, completion: nil)

and the function

func finishAlert(alert: UIAlertAction!)
{
}

In Swift 4 :

let alert=UIAlertController(title:"someAlert", message: "someMessage", preferredStyle:UIAlertControllerStyle.alert )

alert.addAction(UIAlertAction(title: "ok", style: UIAlertActionStyle.default, handler: {
        _ in print("FOO ")
}))

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

Functions are first-class objects in Swift. So if you don't want to use a closure, you can also just define a function with the appropriate signature and then pass it as the handler argument. Observe:

func someHandler(alert: UIAlertAction!) {
    // Do something...
}

alert.addAction(UIAlertAction(title: "Okay",
                              style: UIAlertActionStyle.Default,
                              handler: someHandler))

Syntax change in swift 3.0

alert.addAction(UIAlertAction(title: "Okay",
                style: .default,
                handler: { _ in print("Foo") } ))

Lets assume that you want an UIAlertAction with main title, two actions (save and discard) and cancel button:

let actionSheetController = UIAlertController (title: "My Action Title", message: "", preferredStyle: UIAlertControllerStyle.ActionSheet)

    //Add Cancel-Action
    actionSheetController.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))

    //Add Save-Action
    actionSheetController.addAction(UIAlertAction(title: "Save", style: UIAlertActionStyle.Default, handler: { (actionSheetController) -> Void in
        print("handle Save action...")
    }))

    //Add Discard-Action
    actionSheetController.addAction(UIAlertAction(title: "Discard", style: UIAlertActionStyle.Default, handler: { (actionSheetController) -> Void in
        print("handle Discard action ...")
    }))

    //present actionSheetController
    presentViewController(actionSheetController, animated: true, completion: nil)

This works for swift 2 (Xcode Version 7.0 beta 3)


You can do it as simple as this using swift 2:

let alertController = UIAlertController(title: "iOScreator", message:
        "Hello, world!", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Destructive,handler: { action in
        self.pressed()
}))

func pressed()
{
    print("you pressed")
}

    **or**


let alertController = UIAlertController(title: "iOScreator", message:
        "Hello, world!", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Destructive,handler: { action in
      print("pressed")
 }))

All the answers above are correct i am just showing another way that can be done.


this is how i do it with xcode 7.3.1

// create function
func sayhi(){
  print("hello")
}

// create the button

let sayinghi = UIAlertAction(title: "More", style: UIAlertActionStyle.Default, handler:  { action in
            self.sayhi()})

// adding the button to the alert control

myAlert.addAction(sayhi);

// the whole code, this code will add 2 buttons

  @IBAction func sayhi(sender: AnyObject) {
        let myAlert = UIAlertController(title: "Alert", message:"sup", preferredStyle: UIAlertControllerStyle.Alert);
        let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:nil)

        let sayhi = UIAlertAction(title: "say hi", style: UIAlertActionStyle.Default, handler:  { action in
            self.sayhi()})

        // this action can add to more button
        myAlert.addAction(okAction);
        myAlert.addAction(sayhi);

        self.presentViewController(myAlert, animated: true, completion: nil)
    }

    func sayhi(){
        // move to tabbarcontroller
     print("hello")
    }

Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to uialertview

UIAlertView first deprecated IOS 9 UIAlertController custom font, size, color How to add an action to a UIAlertView button using Swift iOS Writing handler for UIAlertAction How would I create a UIAlertView in Swift? Display UIViewController as Popup in iPhone Adding a simple UIAlertView

Examples related to swift

Make a VStack fill the width of the screen in SwiftUI Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Command CompileSwift failed with a nonzero exit code in Xcode 10 Convert Json string to Json object in Swift 4 iOS Swift - Get the Current Local Time and Date Timestamp Xcode 9 Swift Language Version (SWIFT_VERSION) How do I use Safe Area Layout programmatically? How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator Safe Area of Xcode 9 The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

Examples related to uialertcontroller

UIAlertView first deprecated IOS 9 Get input value from TextField in iOS alert in Swift How to present UIAlertController when not in a view controller? UIAlertController custom font, size, color Presenting a UIAlertController properly on an iPad using iOS 8 Writing handler for UIAlertAction How would I create a UIAlertView in Swift?