How do I handle the actions of a UIAlertController?

Viewed 30108

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];
    }
3 Answers

UIAlertView Controller with multiple textFields.

 @IBAction func showAlert(_ sender: UIButton) {
        let alert = UIAlertController(title: "Registration", message: "Enter your name!", preferredStyle: .alert)
        alert.addTextField { (textField1: UITextField) in
            textField1.placeholder = "John"
        }
        alert.addTextField { (textField2: UITextField) in
            textField2.placeholder = "Doe"
        }
        alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction) in
            if let textField1 = alert.textFields?.first {
                if textField1.text == "" {
                    print("you have to enter something first")
                }else {
                    print("Hello \(textField1.text!)")
                }
            }
            if let textField2 = alert.textFields?.first {
                if textField2.text == "" {
                    print("you have to enter something first")
                }else {
                    print("Hello \(textField2.text!)")
                }
            }
        }))

        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
        self.present(alert, animated: true, completion: nil)
    }
Related