您的位置:首页 > 产品设计 > UI/UE

给UIAlertView UIActionSheet 添加block支持

2013-10-18 00:23 274 查看
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的同学请自行下载吧

XYQuickDevelop

dome 在点击Something里
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: