Taming UIAlertView

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.

ETAlertView *view = [[ETAlertView alloc] initWithTitle:@"Alert" message:@"Hello World!"];
[view addButtonWithTitle:@"OK" callback:^{
    NSLog(@"OK tapped");
}];
[view addButtonWithTitle:@"Cancel" callback:^{
    NSLog(@"Cancel tapped");
}];

Sounds interesting? Here’s the code that you can drop in to your project.

//
//  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

Published by

Umar Ashfaq

Umar Ashfaq is a full-stack web developer. His core strength is building neat UIs with JavaScript on web but he also enjoys server side Java, NodeJS and Objective C. Follow him on twitter @umarashfaq87

Leave a Reply

Your email address will not be published. Required fields are marked *