block是个好语法, 可偏偏 IOS 原生的UIAlertView UIActionSheet不支持block,本文将给上述个类添加block的支持,
.h文件
-(void) handlerClickedButton:(void (^)(NSInteger btnIndex))aBlock;
-(void) handlerClickedButton:(void (^)(NSInteger btnIndex))aBlock{ self.delegate = self; objc_setAssociatedObject(self, UIActionSheet_key_clicked, aBlock, OBJC_ASSOCIATION_COPY); } -(void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{ void (^block)(NSInteger btnIndex) = objc_getAssociatedObject(self, UIActionSheet_key_clicked); if (block) block(buttonIndex); }
@interface UIAlertView (Block) -(void) handlerClickedButton:(void (^)(NSInteger btnIndex))aBlock; -(void) handlerCancel:(void (^)(void))aBlock; -(void) handlerWillPresent:(void (^)(void))aBlock; -(void) handlerDidPresent:(void (^)(void))aBlock; -(void) handlerWillDismiss:(void (^)(NSInteger btnIndex))aBlock; -(void) handlerDidDismiss:(void (^)(NSInteger btnIndex))aBlock; -(void) handlerShouldEnableFirstOtherButton:(BOOL (^)(void))aBlock; @end
@interface UIActionSheet (Block) -(void) handlerClickedButton:(void (^)(NSInteger btnIndex))aBlock; -(void) handlerCancel:(void (^)(void))aBlock; -(void) handlerWillPresent:(void (^)(void))aBlock; -(void) handlerDidPresent:(void (^)(void))aBlock; -(void) handlerWillDismiss:(void (^)(void))aBlock; -(void) handlerDidDismiss:(void (^)(NSInteger btnIndex))aBlock; @end
UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:@"title" message:@"msg" delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil] autorelease]; [alertView handlerClickedButton:^(NSInteger btnIndex) { NSLogD(@"%d", btnIndex); }]; [alertView show];
需要dome的同学请自行下载吧
XYQuickDevelop
dome 在点击Something里