目前,我在UIAlertView
这里和那里弹出了一门课程。目前,同一个类是这些的代表(这将是非常合乎逻辑的)。不幸的是,这些UIAlertView
s 将调用该类的相同委托方法。现在,问题是 - 你怎么知道委托方法是从哪个警报视图调用的?我想只检查警报视图的标题,但这并不优雅。UIAlertView
处理几个s最优雅的方法是什么?
5 回答
像这样标记UIAlertView
s:
#define kAlertViewOne 1
#define kAlertViewTwo 2
UIAlertView *alertView1 = [[UIAlertView alloc] init...
alertView1.tag = kAlertViewOne;
UIAlertView *alertView2 = [[UIAlertView alloc] init...
alertView2.tag = kAlertViewTwo;
然后使用这些标签在委托方法中区分它们:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if(alertView.tag == kAlertViewOne) {
// ...
} else if(alertView.tag == kAlertViewTwo) {
// ...
}
}
仅供参考,如果您只想针对 iOS 4 用户(这是合理的,因为大约 98.5% 的客户端至少安装了 iOS 4),您应该能够使用 Blocks 对 UIAlertViews 进行非常好的内联处理。
这是一个解释它的 Stackoverflow 问题:
Block for UIAlertViewDelegate
为此,我尝试使用 Zachary Waldowski 的 BlocksKit 框架。他的UIAlertView(BlocksKit) API参考看起来非常好。但是,我尝试按照他的指示将 BlocksKit 框架导入我的项目,但不幸的是我无法让它工作。
所以,正如 Can Berk Güder 所建议的,我UIAlertView
现在已经使用了标签。但在未来的某个时候,我将尝试转向使用 Blocks(最好是支持 ARC 开箱即用的)!
更容易和更新
UIAlertView *alert = [[UIAlertView alloc] init...
alert.tag = 1;
UIAlertView *alert = [[UIAlertView alloc] init...
alert.tag = 2;
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if(alertView.tag == 1) {
// first alert...
} else {
// sec alert...
}
}
全部完成!
You can overcome this whole ordeal and prevent yourself from using tags by enhancing UIAlertView to use block callbacks. Check out this blog post I wrote on the subject.
我一直认为使用标签有点小技巧。如果你确实使用它们,至少为标签号设置一些定义的常量。
相反,我使用这样的属性:
在界面部分:
@property (nonatomic, weak) UIAlertView *overDueAlertView;
@property (nonatomic, weak) UIAlertView *retryPromptAlertView;
创建警报视图:
UIAlertView *alert = [[UIAlertView alloc] init...
self.overDueAlertView = alert;
[alert show];
委托方式:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (alertView == self.overDueAlertView) {
// Overdue alert
} else if (alertView == self.retryPromptAlertView) {
// Retry alert
}