Up until iOS 7 we could use the UIAlertView and UIActionSheet classes to bring up alerts and action sheets respectively. As of iOS 8 those classes are deprecated. Although they still work, we’re encouraged to use the UIActionController class instead. Here’s how to use it.
The main difference is that both of the old classes have been converged into one, so now we simply tell the alert controller how we want to bring up the information.
While the old classes used a delegate protocol so we could react to the outcome of user interactions, the UIActionController class uses completion blocks, making our coding efforts a little easier. All we have to do is create an action, specify things like title, subtitle and appearance, and add a block that shall be executed upon completion.
The cancel button is always index 0, and all other buttons in the array start at index 1 counting up.
For completion, here’s how to create it:
// create an alert view with three buttons
UIAlertView*alertView=[[UIAlertViewalloc]initWithTitle:@"Three Button Alert" message:@"This is an alert view with more than two buttons. Will it work?" delegate:self cancelButtonTitle:@"No Way (0)" otherButtonTitles:@"Perhaps (1)",@"Definitely! (2)",nil];
If your class creates more than one UIAlertView, then you need a way to react to each of those accordingly. Problem is, you may only have one delegate that listens to all alerts at any given time.
You could of course create a separate class for each alert view, but that’s a bit overkill. Instead, the UIView’s tag property comes in handy with which you can identify a view at runtime (and UIAlertView inherits from UIView).
tag is an integer so you can only give it whole numbers, like so:
An alert view has the clickedButtonAtIndex property. The first clicked button is 0, the next one 1, and so forth. If you conform to the UIAlertViewDelegate protocol you can implement the following method and react to each pressed button accordingly, or simply call a method: Continue reading →
If you’re conforming to the UIWebViewDelegate protocol the webView:didFailLoadWithError: method gets triggered when there has been a problem.
Call it like this and display an error message (in this case a UIAlertView):
Here’s how we can create a simple pop-up window via the UIAlertView instance. It can have a title, some info text and several buttons (OK, Cancel, etc). We’ll only deal with one button and not worry about how to read out which button value has been pressed.