系统自带的UIAlertView只能支持delegate方式. 如果你只有一个UIAlertView这种方式可能无关紧要. 但如果你有二个或多个UIAlertView, 你需要在委托方法中进行判断是哪个UIAlertView实例的产生的委托, 接着又要判断是响应哪个button. 如果你曾经这样做过, 想想这是多杂的代码. Objective-C是支持块代码的, 如果对UIAlertView添加块支持, 那岂不是一个美事.
这里推荐一个开源的实现: https://github.com/jivadevoe/UIAlertView-Blocks
如果你的项目使用Cocoapods管理. 在Podfile添加下面代码增加支持
pod "UIAlertView-Blocks", "~> 1.0"
再使用命令更新
pod update
使用方式
// 添加头文件
#import <UIAlertView+Blocks.h>
NSString *title = NSLocalizedString(@"Alert", nil);
NSString *message = NSLocalizedString(@"UIAlertView-Blocks", nil);
NSString *cancelButtonTitle = NSLocalizedString(@"Cancel", nil);
NSString *otherTitle = NSLocalizedString(@"OK", nil);
RIButtonItem *cancelButtonItem = [RIButtonItem itemWithLabel:cancelButtonTitle action:^{
NSLog(@"Press Button Cancel");
}];
RIButtonItem *otherButtonItem = [RIButtonItem itemWithLabel:otherTitle action:^{
NSLog(@"Press Button OK");
}];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message cancelButtonItem:cancelButtonItem otherButtonItems:otherButtonItem, nil];
[alert show];
除了这种使用方式, UIAlertView-Blocks还支持其它方法, 可以参考一下它的github主页.