利用runtime实现UIAlertView的block回调

来源:互联网 发布:淘宝中文国际版app 编辑:程序博客网 时间:2024/06/03 02:30

平时我们用UIAlertView需要使用其代理方法来确定我们的点击事件,使用起来不够方便,新的sdkUIAlertViewController是使用block来访问其点击事件的,那我们就将UIAlertView也封装成可以利用block来访问点击事件的类别

首先我们需要一个block属性值

@interface UIAlertView () <UIAlertViewDelegate>


@property (copy,nonatomic) void (^block)(UIAlertView *UIAlertView,NSInteger buttonIndex);


@end

UIAlertView添加按钮是一个个添加,我们可以利用数组来添加

- (instancetype)initWithTitle:(NSString *)title message:(NSString *)message

            cancelButtonTitle:(NSString *)cancelButtonTitle

            otherButtonTitles:(NSArray *)otherButtonTitles

{

    self = [selfinitWithTitle:title message:message

                      delegate:nil

             cancelButtonTitle:cancelButtonTitleotherButtonTitles:nil];

    if (self) {

        for (NSString *otherButtonTitlein otherButtonTitles) {

            [selfaddButtonWithTitle:otherButtonTitle];

        }

    }


    return self;

}


alertViewblock关联起来(通过runtime)注意:要导入头文件

#import <objc/runtime.h>


- (void)setBlock:(void (^)(UIAlertView *,NSInteger))block

{

    objc_setAssociatedObject(self,@selector(block), block, OBJC_ASSOCIATION_COPY_NONATOMIC);

}


- (void (^)(UIAlertView *, NSInteger))block

{

    return objc_getAssociatedObject(self,@selector(block));

}

当点击alertview 的按钮时

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

{

    if (self.block) {

        self.block(alertView, buttonIndex);

    }

}


下面的方法就是block回调

- (void)showUsingBlock:(void (^)(UIAlertView *,NSInteger))block

{

    self.delegate =self;

    self.block = block;


    [selfshow];

}

通过调用此方法,得到的block回调值来判断当前点击的按钮

 UIAlertView *alert = [[UIAlertViewalloc] initWithTitle:@""message:@"" delegate:nilcancelButtonTitle:@"cancel" otherButtonTitles:@"ok",nil];

            [alert showUsingBlock:^(UIAlertView *alertView,NSInteger buttonIndex) {

            }];





0 0
原创粉丝点击