Skip to content

Instantly share code, notes, and snippets.

@onmyway133
Last active August 29, 2015 14:07
Show Gist options
  • Save onmyway133/305e16f77194d6972844 to your computer and use it in GitHub Desktop.
Save onmyway133/305e16f77194d6972844 to your computer and use it in GitHub Desktop.
FTGAlertController
// .h
#import <Foundation/Foundation.h>
typedef void (^FTGHandler)();
@interface FTGAlertController : NSObject
- (instancetype)initWithTitle:(NSString *)title
message:(NSString *)message;
- (instancetype)initWithTitle:(NSString *)title
message:(NSString *)message
cancelButtonTitle:(NSString *)cancelButtonTitle;
- (void)addButtonWithTitle:(NSString *)buttonTitle handler:(FTGHandler)handler;
- (void)show;
@end
// .m
#import "FTGAlertController.h"
@interface FTGAlertController () <UIAlertViewDelegate>
@property (nonatomic, strong) UIAlertView *alertView;
@property (nonatomic, strong) NSMutableDictionary *buttonToHandlerMapping;
@end
@implementation FTGAlertController
- (instancetype)initWithTitle:(NSString *)title
message:(NSString *)message
{
self = [self initWithTitle:title message:message cancelButtonTitle:nil];
return self;
}
- (instancetype)initWithTitle:(NSString *)title
message:(NSString *)message
cancelButtonTitle:(NSString *)cancelButtonTitle
{
self = [super init];
if (self) {
_alertView = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:cancelButtonTitle
otherButtonTitles:nil];
_buttonToHandlerMapping = [NSMutableDictionary dictionary];
}
return self;
}
- (void)addButtonWithTitle:(NSString *)buttonTitle handler:(FTGHandler)handler
{
[self.alertView addButtonWithTitle:buttonTitle];
if (handler) {
[self.buttonToHandlerMapping setObject:[handler copy] forKey:buttonTitle];
}
}
- (void)show
{
[self.alertView show];
}
#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *buttonTitle = [alertView buttonTitleAtIndex:buttonIndex];
FTGHandler handler = self.buttonToHandlerMapping[buttonTitle];
if (handler) {
handler();
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment