Alert view in iphone

Viewed 78759

I am new to iPhone application development. I want to design an alert view with 2 buttons: OK and Cancel. When the user touches the OK button, then I will print a message that says hello. When they touch the Cancel button, I will print cancel.

Please help; how do I do this?

7 Answers

enter image description here

For Objective C:

UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"My Alert"
            message:@"This is an action sheet." 
            preferredStyle:UIAlertControllerStyleAlert]; // 1
    UIAlertAction *firstAction = [UIAlertAction actionWithTitle:@"one"
            style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
                NSLog(@"You pressed button one");
            }]; // 2
    UIAlertAction *secondAction = [UIAlertAction actionWithTitle:@"two"
            style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
                NSLog(@"You pressed button two");
            }]; // 3

    [alert addAction:firstAction]; // 4
    [alert addAction:secondAction]; // 5

    [self presentViewController:alert animated:YES completion:nil]; // 6

For Swift:

let alert = UIAlertController(title: "My Alert", message: "This is an action sheet.", preferredStyle: .Alert) // 1
    let firstAction = UIAlertAction(title: "one", style: .Default) { (alert: UIAlertAction!) -> Void in
        NSLog("You pressed button one")
    } // 2

    let secondAction = UIAlertAction(title: "two", style: .Default) { (alert: UIAlertAction!) -> Void in
        NSLog("You pressed button two")
    } // 3

    alert.addAction(firstAction) // 4
    alert.addAction(secondAction) // 5
    presentViewController(alert, animated: true, completion:nil) // 6

Related