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里
本文介绍如何为 iOS 中的 UIAlertView 和 UIActionSheet 添加 block 支持,通过这种方式可以更简洁地处理按钮点击等事件。文章提供了具体的 .h 和 .m 文件实现示例,并展示了如何在代码中调用这些新添加的方法。
1万+

被折叠的 条评论
为什么被折叠?



