How to implement a pop-up dialog box in iOS?

319,253

Solution 1

Yup, a UIAlertView is probably what you're looking for. Here's an example:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No network connection" 
                                                message:@"You must be connected to the internet to use this app." 
                                               delegate:nil 
                                      cancelButtonTitle:@"OK"
                                      otherButtonTitles:nil];
[alert show];
[alert release];

If you want to do something more fancy, say display a custom UI in your UIAlertView, you can subclass UIAlertView and put in custom UI components in the init method. If you want to respond to a button press after a UIAlertView appears, you can set the delegate above and implement the - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex method.

You might also want to look at the UIActionSheet.

Solution 2

Different people who come to this question mean different things by a popup box. I highly recommend reading the Temporary Views documentation. My answer is largely a summary of this and other related documentation.

Alert (show me an example)

enter image description here

Alerts display a title and an optional message. The user must acknowledge it (a one-button alert) or make a simple choice (a two-button alert) before going on. You create an alert with a UIAlertController.

It is worth quoting the documentation's warning and advice about creating unnecessary alerts.

enter image description here

Notes:

Action Sheet (show me an example)

enter image description here

Action Sheets give the user a list of choices. They appear either at the bottom of the screen or in a popover depending on the size and orientation of the device. As with alerts, a UIAlertController is used to make an action sheet. Before iOS 8, UIActionSheet was used, but now the documentation says:

Important: UIActionSheet is deprecated in iOS 8. (Note that UIActionSheetDelegate is also deprecated.) To create and manage action sheets in iOS 8 and later, instead use UIAlertController with a preferredStyle of UIAlertControllerStyleActionSheet.

Modal View (show me an example)

enter image description here

A modal view is a self-contained view that has everything it needs to complete a task. It may or may not take up the full screen. To create a modal view, use a UIPresentationController with one of the Modal Presentation Styles.

See also

Popover (show me an example)

enter image description here

A Popover is a view that appears when a user taps on something and disappears when tapping off it. It has an arrow showing the control or location from where the tap was made. The content can be just about anything you can put in a View Controller. You make a popover with a UIPopoverPresentationController. (Before iOS 8, UIPopoverController was the recommended method.)

In the past popovers were only available on the iPad, but starting with iOS 8 you can also get them on an iPhone (see here, here, and here).

See also

Notifications

enter image description here

Notifications are sounds/vibrations, alerts/banners, or badges that notify the user of something even when the app is not running in the foreground.

enter image description here

See also

A note about Android Toasts

enter image description here

In Android, a Toast is a short message that displays on the screen for a short amount of time and then disappears automatically without disrupting user interaction with the app.

People coming from an Android background want to know what the iOS version of a Toast is. Some examples of these questions can he found here, here, here, and here. The answer is that there is no equivalent to a Toast in iOS. Various workarounds that have been presented include:

  • Make your own with a subclassed UIView
  • Import a third party project that mimics a Toast
  • Use a buttonless Alert with a timer

However, my advice is to stick with the standard UI options that already come with iOS. Don't try to make your app look and behave exactly the same as the Android version. Think about how to repackage it so that it looks and feels like an iOS app.

Solution 3

Since the release of iOS 8, UIAlertView is now deprecated; UIAlertController is the replacement.

Here is a sample of how it looks in Swift:

let alert = UIAlertController(title: "Hello!", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
let alertAction = UIAlertAction(title: "OK!", style: UIAlertActionStyle.default)
{
    (UIAlertAction) -> Void in
}
alert.addAction(alertAction)
present(alert, animated: true)
{
    () -> Void in
}

As you can see, the API allows us to implement callbacks for both the action and when we are presenting the alert, which is quite handy!

Updated for Swift 4.2

let alert = UIAlertController(title: "Hello!", message: "Message", preferredStyle: .alert)
let alertAction = UIAlertAction(title: "OK!", style: .default)
        {
            (UIAlertAction) -> Void in
        }
        alert.addAction(alertAction)
        present(alert, animated: true)
        {
            () -> Void in
        }

Solution 4

Since iOS 8.0, you will need to use UIAlertController as the following:

-(void)alertMessage:(NSString*)message
{
    UIAlertController* alert = [UIAlertController
          alertControllerWithTitle:@"Alert"
          message:message
          preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction* defaultAction = [UIAlertAction 
          actionWithTitle:@"OK" style:UIAlertActionStyleDefault
         handler:^(UIAlertAction * action) {}];

    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
}
  

Where self in my example is a UIViewController, which implements "presentViewController" method for a popup.

Solution 5

For Swift 3 & Swift 4 :

Since UIAlertView is deprecated, there is the good way for display Alert on Swift 3

let alertController = UIAlertController(title: NSLocalizedString("No network connection",comment:""), message: NSLocalizedString("connected to the internet to use this app.",comment:""), preferredStyle: .alert)
let defaultAction = UIAlertAction(title:     NSLocalizedString("Ok", comment: ""), style: .default, handler: { (pAlert) in
                //Do whatever you want here
        })
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)

Deprecated :

This is the swift version inspired by the checked response :

Display AlertView :

   let alert = UIAlertView(title: "No network connection", 
                           message: "You must be connected to the internet to use this app.", delegate: nil, cancelButtonTitle: "Ok")
    alert.delegate = self
    alert.show()

Add the delegate to your view controller :

class AgendaViewController: UIViewController, UIAlertViewDelegate

When user click on button, this code will be executed :

func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {


}
Share:
319,253

Related videos on Youtube

Namratha
Author by

Namratha

Updated on September 09, 2021

Comments

  • Namratha
    Namratha over 2 years

    After a calculation, I want to display a pop up or alert box conveying a message to the user. Does anyone know where I can find more information about this?

  • JOM
    JOM about 12 years
    Apple documentation says "The UIAlertView class is intended to be used as-is and does not support subclassing". developer.apple.com/library/ios/#documentation/uikit/referen‌​ce/…
  • Javier Sedano
    Javier Sedano over 11 years
    Just a comment: with ARC enabled, the '[alert release]' is not needed (at least, the compiler says so).
  • xySVerma
    xySVerma over 11 years
    Subclassing UIAlertView is not supported iOS 4 onwards
  • guilherme.minglini
    guilherme.minglini over 10 years
    Here is an example of a simple UIAlertView with delegate, if you also need the buttons actions
  • Radu Simionescu
    Radu Simionescu about 10 years
    @SourabhVerma that is simply NOT true
  • Rogerio Chaves
    Rogerio Chaves over 9 years
    In case you are looking for a swift version, check out Oscar Swanros' answer
  • Jeff Mascia
    Jeff Mascia over 9 years
    If UIAlertView is too restrictive for your use case, you should try my KLCPopup class. It lets you present any custom UIView as a popup. It supports a variety of show/hide animations, relative/explicit layout options, background touch handling, etc.
  • Andrew Plummer
    Andrew Plummer almost 9 years
    @Entalpi Should presentViewController have a closing brace and what is the difference between your completion block and just having completion:nil ?
  • Entalpi
    Entalpi almost 9 years
    It no difference. It there exists a block to call it will be called.
  • Filipe Brito
    Filipe Brito over 8 years
    With a note about Android Toast still! Nice! This information helps new developers that comes from Android development. Thank you!
  • Parth Sane
    Parth Sane about 7 years
    UIAlertView is now deprecated.
  • finngu
    finngu almost 7 years
    Man, I need to print and frame this! You saved me yesterday and today again :D
  • Lucas van Dongen
    Lucas van Dongen over 6 years
    Please update your answer to use UIAlertController instead
  • Daniel Nord
    Daniel Nord almost 3 years
    And then you have Contextual Cards like the one that is displayed when connecting to AirPods. github.com/alexisakers/BulletinBoard
  • Awais Khan
    Awais Khan over 2 years
    What an explanation this is. You are a superstar man. Great work