平時我們用UIAlertView需要使用其代理方法來確定我們的點擊事件,使用起來不夠方便,新的sdk中UIAlertViewController是使用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;
}
將alertView與block關聯起來(通過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) {
}];