当前位置: 首页 > 科技观察

iOS9中提示框的正确实现方法

时间:2023-03-13 19:03:42 科技观察

iOS8到iOS9的升级过程中,弹出提示框的方式发生了很大的变化。在Xcode7和iOS9.0SDK中,已经明确表示不再推荐使用UIAlertView,只能使用UIAlertController,下面通过代码来演示一下。我点击一个按钮,然后弹出一个提示框。代码示例如下:[objc]viewplaincopyprint?#import"ViewController.h"@interfaceViewController()@property(strong,nonatomic)UIButton*button;@end@implementationViewController-(void)viewDidLoad{[superviewDidLoad];self.button=[[UIButtonalloc]initWithFrame:CGRectMake(0,100,[[UIScreenmainScreen]bounds].size.width,20)];[self.buttonsetTitle:@"jump"forState:UIControlStateNormal];[self.buttonsetTitleColor:[UIColorblackColor]forState:UIControlStateNormal];[self.viewaddSubview:self.button];[self.buttonaddTarget:selfaction:@selector(clickMe:)forControlEvents:UIControlEventTouchUpInside];}-(void)clickMe:(id)sender{UIAlertView*alert=[[UIAlertViewalloc]initWithTitle:@"提示"message:@"按钮被点击"delegate:selfcancelButtonTitle:@"OK"otherButtonTitles:nil,nilnil];[alertshow];}@end写上面代码,会有如下警告提示:"'UIAlertView'isdeprecated:firstdeprecatediniOS9.0-UIAlertViewisdeprecated.UseUIAlertControllerwithareferredStyleofUIAlertControllerStyleAlertinstead”。表示UIAlertView在iOS9中首先被deprecated(不推荐)。让我们使用UIAlertController。但是当我们运行程序时,我们发现代码仍然可以成功运行而没有崩溃。但是在实际工程开发中,我们有这个一个“潜规则”:把每一个警告都当成一个错误。所以为了顺应Apple的潮流,我们解决这个警告,用UIAlertController来解决这个问题。代码如下:[objc]viewplaincopyprint?#import"ViewController.h"@interfaceViewController()@property(strong,nonatomic)UIButton*button;@end@implementationViewController-(void)viewDidLoad{[superviewDidLoad];self.button=[[UIButtonalloc]initWithFrame:CGRectMake(0,100,[[UIScreenmainScreen]bounds].size.width,20)];[self.buttonsetTitle:@"jump"forState:UIControlStateNormal];[self.buttonsetTitleColor:[UIColorblackColor]forState:UIControlStateNormal];[self.viewaddSubview:self.button];[self.buttonaddTarget:selfaction:@selector(clickMe:)forControlEvents:UIControlEventTouchUpInside];}-(void)clickMe:(id)sender{//初始化提示框;UIAlertController*alert=[UIAlertControlleralertControllerWithTitle:@"prompt"message:@"buttonwasclicked"preferredStyle:UIAlertControllerStyleAlert];[alertaddAction:[UIAlertActionactionWithTitle:@"OK"style:UIAlertActionStyleDefaulthandler:^(UIAlertAction*_Nonnullaction){//点击按钮响应event;}]];//弹出提示框;[selfpresentViewController:alertanimated:truecompletion:nil];}@end这样代码就不会出现警告了。程序运行后,效果同上。preferredStyle参数有另一个选项:UIAlertControllerStyleActionSheet。选择这个枚举类型后,效果如下:发现从底部弹出了提示框。是不是很简单?通过查看代码也可以发现,提示框中的按钮响应不再需要委托来实现。直接使用addAction实现块中的按钮点击,非常方便。