为UIAlertView添加block支持

系统自带的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主页.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值