利用runtime实现UIAlertView的block回调

平时我们用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 = [self initWithTitle:title message:message

                      delegate:nil

             cancelButtonTitle:cancelButtonTitle otherButtonTitles:nil];

    if (self) {

        for (NSString *otherButtonTitle in otherButtonTitles) {

            [self addButtonWithTitle: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;


    [self show];

}

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

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

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

            }];





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值