iOS9使用提示框的正確實現方式(UIAlertView is deprecated)
前言
在從iOS8到iOS9的升級過程中,彈出提示框的方式有了很大的改變,在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
需要注意的是
在iOS 9.0 SDK 環境下編譯上述程式碼時,會有下列的警告提示:
“‘UIAlertView’ is deprecated:first deprecated in iOS 9.0 - UIAlertView is deprecated. Use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert instead”
意思是UIAlertView首先在iOS9中被棄用(不推薦)使用。讓我們去用UIAlertController。但是執行程式,發現程式碼還是可以成功執行,不會出現crash。
解決這個warning,使用UIAlertController來解決這個問題。程式碼如下
//初始化提示框;
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"按鈕被點選了" preferredStyle: UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//點選按鈕的響應事件;
}]];
//彈出提示框;
[self presentViewController:alert animated:true completion:nil];
這樣,程式碼就不會有警告了。
程式執行後的效果同上。
其中preferredStyle這個引數還有另一個選擇UIAlertControllerStyleActionSheet
選擇這個列舉型別後,發現這個提示框是從底部彈出的。通過檢視程式碼還可以發現,在提示框中的按鈕響應不再需要delegate委託來實現了。直接使用addAction就可以在一個block中實現按鈕點選,非常方便。
總結
可以發現這裡我們呈現一個對話方塊使用了presentViewController這個方法,這個方法是呈現模態檢視(Modal View)的方法,也就是是說,此時的提示框是一個模態檢視。當我們在進行介面跳轉的時候,也一般使用這個方法,此時呈現的第二個ViewController也是一個模態檢視。我們可以把模態檢視理解為一個浮動在原先檢視上的一個臨時性的檢視或者介面,當在模態檢視中呼叫dismissViewController方法時,會返回上一個介面,並銷燬這個模態檢視物件。