[Objc] UIAlertView and blocks

A simple UIAlertView category to show an alert view in a simple and more readable way!

Like this:

[code autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”][ UIAlertView showAlertViewWithTitle:@"title"
message:@"message alert"
cancelButtonTitle:@"cancel"
otherButtonTitles:@[@"ok"]
onSelect:^(int buttonIndex) {
NSLog(@"DISMISSED!!!");
} onCancel:^{
NSLog(@"CANCELLED!");
}];[/code]

Schermata 2013-10-21 alle 17.32.38

 

How to?

Create your UIAlertView+Blocks category and import in your file projects:

[code autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”]//
// header
//
@interface UIAlertView (BlockBased)

typedef void (^SelectBlock)(int buttonIndex);
typedef void (^CancelBlock)();

+ (UIAlertView*) showAlertViewWithTitle:(NSString*) title
message:(NSString*) message
cancelButtonTitle:(NSString*) cancelButtonTitle
otherButtonTitles:(NSArray*) otherButtons
onSelect:(SelectBlock) selected
onCancel:(CancelBlock) cancelled;

@end[/code]

[code autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”]//
// implementation
//
@implementation UIAlertView (BlockBased)

static SelectBlock  _selectBlock;
static CancelBlock  _cancelBlock;

+ (UIAlertView*) showAlertViewWithTitle:(NSString*) title
message:(NSString*) message
cancelButtonTitle:(NSString*) cancelButtonTitle
otherButtonTitles:(NSArray*) otherButtons
onSelect:(SelectBlock) selected
onCancel:(CancelBlock) cancelled
{
_cancelBlock  =  [cancelled copy];
_selectBlock  =  [selected  copy];

UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:title
message:message
delegate:[self self]
cancelButtonTitle:cancelButtonTitle
otherButtonTitles:nil];

for ( NSString *buttonTitle in otherButtons )
[alert addButtonWithTitle:buttonTitle];

[alert show];

return alert;
}

+ (void)alertView:(UIAlertView*) alertView didDismissWithButtonIndex:(NSInteger) buttonIndex
{
if ( buttonIndex == [alertView cancelButtonIndex] ) _cancelBlock();
else _selectBlock (buttonIndex – 1);
}

@end[/code]

On githubhttps://gist.github.com/elpsk/3d2f5fe1612ff107ad9e

Ref:
– albertopasca.it
– http://goo.gl/ie6ILd

Alberto Pasca
Latest posts by Alberto Pasca (see all)