利用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) {

            }];





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章