Taming UIAlertView

Umar Ashfaq
Eastros
Published in
1 min readMay 1, 2014

There are a few things in iOS development which are surprisingly difficult, UIAlertView is one of them. If your UIAlertView contains only one button, which cancels the dialog, things will be easy. But as soon as you’ll think of adding more buttons to it, you’ll realize that you’ll need to create a delegate class and assign the delegate to the UIAlertView instance. This is ridiculous, because given the frequency of use of UIAlertView, you’ll end up creating unnecessary delegate classes.

So I came up with a simpler solution. I created a simple wrapper class ETAlertView which can contain multiple buttons without creating delegates.
[sourcecode language=”objc”]
ETAlertView *view = [[ETAlertView alloc] initWithTitle:@”Alert” message:@”Hello World!”];
[view addButtonWithTitle:@”OK” callback:^{
NSLog(@”OK tapped”);
}];
[view addButtonWithTitle:@”Cancel” callback:^{
NSLog(@”Cancel tapped”);
}];
[/sourcecode]

Sounds interesting? Here’s the code that you can drop in to your project.
[sourcecode language=”objc”]
//
// ETAlertView.h
//
// Created by Umar Ashfaq on 5/1/14.
//

#import <UIKit/UIKit.h>

typedef void(^CallbackBlock)();

@interface ETAlertView : UIAlertView<UIAlertViewDelegate>
{
NSMutableArray *buttonBlocks;
}

- (id) initWithTitle:(NSString *)title message:(NSString *)message;
- (void) addButtonWithTitle:(NSString *)title callback:(CallbackBlock)block;

@end

//
// ETAlertView.m
//
// Created by Umar Ashfaq on 5/1/14.
//

#import “ETAlertView.h”

@implementation ETAlertView

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}

- (id) initWithTitle:(NSString *)title message:(NSString *)message
{
buttonBlocks = [[NSMutableArray alloc] init];

return [self initWithTitle:title message:message delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
}

- (void) addButtonWithTitle:(NSString *)title callback:(CallbackBlock)block
{
[self addButtonWithTitle:title];
[buttonBlocks addObject:block];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
CallbackBlock block = [buttonBlocks objectAtIndex:buttonIndex];
block();
}

@end
[/sourcecode]

--

--