[ios] Adding a simple UIAlertView

What is some starter code I could use to make a simple UIAlertView with one "OK" button on it?

This question is related to ios objective-c iphone cocoa-touch uialertview

The answer is


This page shows how to add an UIAlertController if you are using Swift.


UIAlertView *myAlert = [[UIAlertView alloc] 
                         initWithTitle:@"Title"
                         message:@"Message"
                         delegate:self
                         cancelButtonTitle:@"Cancel"
                         otherButtonTitles:@"Ok",nil];
[myAlert show];

UIAlertView is deprecated on iOS 8. Therefore, to create an alert on iOS 8 and above, it is recommended to use UIAlertController:

UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Title" message:@"Alert Message" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){

    // Enter code here
}];
[alert addAction:defaultAction];

// Present action where needed
[self presentViewController:alert animated:YES completion:nil];

This is how I have implemented it.


Simple alert with array data:

NSString *name = [[YourArray objectAtIndex:indexPath.row ]valueForKey:@"Name"];

NSString *msg = [[YourArray objectAtIndex:indexPath.row ]valueForKey:@"message"];

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:name
                                                message:msg
                                               delegate:self
                                      cancelButtonTitle:@"OK"
                                      otherButtonTitles:nil];
[alert show];

UIAlertView *alert = [[UIAlertView alloc]
 initWithTitle:@"Title" 
 message:@"Message" 
 delegate:nil //or self
 cancelButtonTitle:@"OK"
 otherButtonTitles:nil];

 [alert show];
 [alert autorelease];

Here is a complete method that only has one button, an 'ok', to close the UIAlert:

- (void) myAlert: (NSString*)errorMessage
{
    UIAlertView *myAlert = [[UIAlertView alloc]
                          initWithTitle:errorMessage
                          message:@""
                          delegate:self
                          cancelButtonTitle:nil
                          otherButtonTitles:@"ok", nil];
    myAlert.cancelButtonIndex = -1;
    [myAlert setTag:1000];
    [myAlert show];
}

Other answers already provide information for iOS 7 and older, however UIAlertView is deprecated in iOS 8.

In iOS 8+ you should use UIAlertController. It is a replacement for both UIAlertView and UIActionSheet. Documentation: UIAlertController Class Reference. And a nice article on NSHipster.

To create a simple Alert View you can do the following:

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Title"
                                                                         message:@"Message"
                                                                  preferredStyle:UIAlertControllerStyleAlert];
//We add buttons to the alert controller by creating UIAlertActions:
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok"
                                                   style:UIAlertActionStyleDefault
                                                 handler:nil]; //You can use a block here to handle a press on this button
[alertController addAction:actionOk];
[self presentViewController:alertController animated:YES completion:nil];

Swift 3 / 4 / 5:

let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
//We add buttons to the alert controller by creating UIAlertActions:
let actionOk = UIAlertAction(title: "OK",
    style: .default,
    handler: nil) //You can use a block here to handle a press on this button

alertController.addAction(actionOk)

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

Note, that, since it was added in iOS 8, this code won't work on iOS 7 and older. So, sadly, for now we have to use version checks like so:

NSString *alertTitle = @"Title";
NSString *alertMessage = @"Message";
NSString *alertOkButtonText = @"Ok";

if (@available(iOS 8, *)) {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:alertTitle
                                                        message:alertMessage
                                                       delegate:nil
                                              cancelButtonTitle:nil
                                              otherButtonTitles:alertOkButtonText, nil];
    [alertView show];
}
else {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:alertTitle
                                                                             message:alertMessage
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    //We add buttons to the alert controller by creating UIAlertActions:
    UIAlertAction *actionOk = [UIAlertAction actionWithTitle:alertOkButtonText
                                                       style:UIAlertActionStyleDefault
                                                     handler:nil]; //You can use a block here to handle a press on this button
    [alertController addAction:actionOk];
    [self presentViewController:alertController animated:YES completion:nil];
}

Swift 3 / 4 / 5:

let alertTitle = "Title"
let alertMessage = "Message"
let alertOkButtonText = "Ok"

if #available(iOS 8, *) {
    let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert)
    //We add buttons to the alert controller by creating UIAlertActions:
    let actionOk = UIAlertAction(title: alertOkButtonText,
        style: .default,
        handler: nil) //You can use a block here to handle a press on this button

    alertController.addAction(actionOk)
    self.present(alertController, animated: true, completion: nil)
}
else {
    let alertView = UIAlertView(title: alertTitle, message: alertMessage, delegate: nil, cancelButtonTitle: nil, otherButtonTitles: alertOkButtonText)
    alertView.show()
}

UPD: updated for Swift 5. Replaced outdated class presence check with availability check in Obj-C.


As a supplementary to the two previous answers (of user "sudo rm -rf" and "Evan Mulawski"), if you don't want to do anything when your alert view is clicked, you can just allocate, show and release it. You don't have to declare the delegate protocol.


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 objective-c

Adding a UISegmentedControl to UITableView Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Warp \ bend effect on a UIView? Use NSInteger as array index Detect if the device is iPhone X Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3 ITSAppUsesNonExemptEncryption export compliance while internal testing? How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem? Change status bar text color to light in iOS 9 with Objective-C

Examples related to iphone

Detect if the device is iPhone X Xcode 8 shows error that provisioning profile doesn't include signing certificate Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone Certificate has either expired or has been revoked Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve? cordova run with ios error .. Error code 65 for command: xcodebuild with args: "Could not find Developer Disk Image" Reason: no suitable image found iPad Multitasking support requires these orientations How to insert new cell into UITableView in Swift

Examples related to cocoa-touch

Include of non-modular header inside framework module Move textfield when keyboard appears swift Create space at the beginning of a UITextField Navigation bar with UIImage for title Generate a UUID on iOS from Swift How do I write a custom init for a UIView subclass in Swift? creating custom tableview cells in swift How would I create a UIAlertView in Swift? Get current NSDate in timestamp format How do you add an in-app purchase to an iOS application?

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