block是个好语法, 可偏偏 IOS 原生的UIAlertView UIActionSheet不支持block,本文将给上述个类添加block的支持,
.h文件
-(void) handlerClickedButton:(void (^)(NSInteger btnIndex))aBlock;
.m文件
-(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);
}
按照这种思路将UIAlertView,UIActionSheet 委托全部重写一遍
@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];
其实真这样全部改造下了发先也没简化多少,ui的代码和业务逻辑的代码混在一起了,反而代码更加混乱.
需要dome的同学请自行下载吧
dome 在点击Something里