在Xcode7 ,iOS9.0的SDK中,已经明确提示不再推荐使用UIAlertView,而只能使用UIAlertController;
之前弹出提示框的示例代码如下:
#import "ViewController.h"
@interface ViewController ()
@property(strong,nonatomic) UIButton *button;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.button = [[UIButton alloc] initWithFrame:CGRectMake(0, 100, [[UIScreen mainScreen] bounds].size.width, 20)];
[self.button setTitle:@"跳转" forState:UIControlStateNormal];
[self.button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.view addSubview:self.button];
[self.button addTarget:self action:@selector(clickMe:) forControlEvents:UIControlEventTouchUpInside];
}
-(void)clickMe:(id)sender{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"按钮被点击了" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil nil];
[alert show];
}
@end
但是会有警告‘UIAlertView’ is deprecated:first deprecated in iOS 9.0 - UIAlertView is deprecated.
表明UIAlertView已经iOS9中被弃用(不推荐)使用。推荐使用UIAlertController。
为解决这个warning,使用UIAlertController来解决这个问题。代码如下:
#import "ViewController.h"
@interface ViewController ()
@property(strong,nonatomic) UIButton *button;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.button = [[UIButton alloc] initWithFrame:CGRectMake(0, 100, [[UIScreen mainScreen] bounds].size.width, 20)];
[self.button setTitle:@"跳转" forState:UIControlStateNormal];
[self.button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.view addSubview:self.button];
[self.button addTarget:self action:@selector(clickMe:) forControlEvents:UIControlEventTouchUpInside];
}
-(void)clickMe:(id)sender{
//初始化提示框;
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"按钮被点击了" preferredStyle: UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//点击按钮的响应事件;
}]];
//弹出提示框;
[self presentViewController:alert animated:true completion:nil];
}
@end
通过运行发下,程序运行后的效果相同。 其中preferredStyle
这个参数还有另一个选择:UIAlertControllerStyleActionSheet
。选择这个枚举类型后,实现效果:提示框会从底部弹出。
对比:通过查看代码还可以发现,在提示框中的按钮响应不再需要delegate委托来实现了。直接使用addAction
就可以在一个block中实现按钮点击,非常方便。