开发iOS经常用到UIAlertView(iOS9废弃了,本文只是以此为例)。当用户按下按钮时需要用委托协议来处理此动作,代码就分成创建警告视图和处理按钮动作两部分。
- (IBAction)askUserQuestion:(UIButton *)sender {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"Question"
message:@"What do you want to ask"
delegate:self
cancelButtonTitle:@"cancel"
otherButtonTitles:@"continue", nil];
[alert show];
}
//UIAlertViewDelegate method
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
NSLog(@"%d", (int)buttonIndex);
}
如果想在同一个类里处理多个UI AlertView,那代码就变得复杂。
要是能在创建警告视图时候直接把处理每个按钮的逻辑都写好就简单多了。这可以用关联对象做。
导入头文件:
#import <objc/runtime.h>
static void *ECOMyAlertViewKey = "ECOMyAlertViewKey";
//ButtonA
- (IBAction)askUserQuestion:(UIButton *)sender {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"Question"
message:@"What do you want to ask"
delegate:self
cancelButtonTitle:@"cancel"
otherButtonTitles:@"continue", nil];
void (^block)(NSInteger) = ^(NSInteger buttonIndex) {
NSLog(@"aa == %d", (int)buttonIndex);
};
objc_setAssociatedObject(alert,
ECOMyAlertViewKey,
block,
OBJC_ASSOCIATION_COPY);
[alert show];
}
//ButtonB
- (IBAction)bButton:(UIButton *)sender {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"ask"
message:@"rrrrrr"
delegate:self
cancelButtonTitle:@"cancel"
otherButtonTitles:@"continue", nil];
void (^block)(NSInteger) = ^(NSInteger buttonIndex) {
NSLog(@"bb == %d", (int)buttonIndex);
};
objc_setAssociatedObject(alert,
ECOMyAlertViewKey,
block,
OBJC_ASSOCIATION_COPY);
[alert show];
}
//UIAlertViewDelegate method
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
NSLog(@"%d", (int)buttonIndex);
void (^block)(NSInteger) = objc_getAssociatedObject(alertView, ECOMyAlertViewKey);
block(buttonIndex);
}