为UIAlertView添加block支持

来源:互联网 发布:淘宝店铺广告语 编辑:程序博客网 时间:2024/05/17 01:03

系统自带的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(@"Set", 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主页.
0 0
原创粉丝点击