平时我们用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) {
}];