原始的UIAlertView的需要通过委托方法来实现按钮点击事件,需要设置代理,实现委托方法,比较繁琐。我们可以自定义一个UIAlertView类,通过block语法替代委托代理,这样的话,使用该自定义的UIAlertView就比较方便了。
BlockUIAlertView.h 文件
typedef void(^AlertBlock)(NSInteger);
@interface BlockUIAlertView : UIAlertView
@property(nonatomic,copy)AlertBlock block;
- (id)initWithTitle:(NSString *)title
message:(NSString *)message
cancelButtonTitle:(NSString *)cancelButtonTitle
clickButton:(AlertBlock)_block
otherButtonTitles:(NSString *)otherButtonTitles;
@end
BlockUIAlertView.m 文件的实现
#import "BlockUIAlertView.h"
@implementation BlockUIAlertView
@synthesize block;
- (id)initWithTitle:(NSString *)title
message:(NSString *)message
cancelButtonTitle:(NSString *)cancelButtonTitle
clickButton:(AlertBlock)_block
otherButtonTitles:(NSString *)otherButtonTitles {
self = [super initWithTitle:title message:message delegate:self cancelButtonTitle:cancelButtonTitle otherButtonTitles:otherButtonTitles,nil];
if (self) {
self.block = _block;
}
return self;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
self.block(buttonIndex);
}
@end
该自定义的BlockUIAlertView的调用
BlockUIAlertView *alertView = [[BlockUIAlertView alloc] initWithTitle:@"提示" message:@"block测试" cancelButtonTitle:@"取消title" clickButton:^(NSInteger indexButton){
NSLog(@"%d",indexButton);
} otherButtonTitles:nil];
[alertView show];