How do I handle the actions of a UIAlertController?

ghoshghosh picture ghoshghosh · Mar 25, 2016 · Viewed 27.8k times · Source

How can I link UIAlertController alert action buttons with action handlers using objective-c? I'm using Xcode 7.1.

Here is my code:

- (IBAction)selectbtn:(UIButton *)sender {

    UIAlertController *alert=[ UIAlertController alertControllerWithTitle:@"NEW" message:@"button pressed" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cameraaction=[UIAlertAction actionWithTitle:@"From camera" style:UIAlertActionStyleDefault handler:nil ];
    [alert addAction:cameraaction];
    UIAlertAction *libraryaction=[UIAlertAction actionWithTitle:@"From photo library" style:UIAlertActionStyleDefault handler:nil ];
    [alert addAction:libraryaction];
    UIAlertAction *cancelaction=[UIAlertAction actionWithTitle:@"cancel" style:UIAlertActionStyleDestructive handler:nil];
    [alert addAction:cancelaction];
    [self presentViewController:alert animated:YES
                     completion:nil];
    }

Answer

Andrey picture Andrey · Mar 25, 2016

Objective-C

UIAlertController works like this:

UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Title" message:@"text mssg" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){
    // Ok action example
}];
UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"Other" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){
    // Other action
}];
[alert addAction:okAction];
[alert addAction:otherAction];
[self presentViewController:alert animated:YES completion:nil];

I think you meant that.

Swift 3.0/4.0

let myalert = UIAlertController(title: "Titulo mensaje", message: "Mi mensaje.", preferredStyle: UIAlertControllerStyle.alert)

myalert.addAction(UIAlertAction(title: "Aceptar", style: .default) { (action:UIAlertAction!) in
        print("Selected")
    })
myalert.addAction(UIAlertAction(title: "Cancelar", style: .cancel) { (action:UIAlertAction!) in
        print("Cancel")
    })

    self.present(myalert, animated: true)