iOS User Alerts and Action Sheets

In Cocoa Touch, you can send alert to the user using the UIAlertView and UIActionSheet classes.


UIAlertView allows you to send messages to the user. The class UIAlertView is used together to the UIAlertViewDelegate protocol. In this way, when the user tap on an alert view button, we can react to that, using the following method:

Or in Swift:

To launch an alert is very simple, you instantiate an alert using the following method:

Or in Swift:

Here, an example on how to use this method:

When the user taps on the Cancel button, the delegate method alertView:clickedButtonAtIndex is executed on the alert view delegate object. The button index depends on the button position. The first button on the left has index 0.


UIActionSheet works in a similar way of the UIAlertView. An action sheet is needed to ask the user to take a decision. Action sheets can be visualized in a view, from a tab bar or from a navigation bar.

If your class uses an action sheet, it must conform to the UIActionSheetDelegate protocol. In this way, you can also implement the following method from the UIActionSheetDelegate protocol:

This method allows us to process the user action. To launch an action is very simple too. Whenever you need an action sheet, you initialize one using the following method:

Here an example on how to use the previous method:

A practical example

Let’s build an iOS application using an alert view. Open Xcode and create a Single-View Application. Call it SimpleAlert. Open the ViewController and add the UIAlertViewDelegate protocol.

Add the following method:

Now, go to Main.storyboard, add a UIButton and connect to the alertViewButtonPressed IBAction. Back in ViewController.m, complete the alertViewButtonPressed method:

Then, implement the following delegate method to notify the delegate when the user clicks a button on an alert view:

Build and run and now, when you press one of the buttons, a message should appear in the console with the button index you pressed.

Have a nice coding,




(Visited 40 times, 1 visits today)