在從iOS8到iOS9的升級過程當中,彈出提示框的方式有了很大的改變,在Xcode7 ,iOS9.0的SDK中,已經明確提示再也不推薦使用UIAlertView,而只能使用UIAlertController,咱們經過代碼來演示一下。ide
我經過點擊一個按鈕,而後彈出提示框,代碼示例以下:atom
#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]; [alert show]; } @end
編寫上述代碼時,會有下列的警告提示:spa
。code
「‘UIAlertView’ is deprecated:first deprecated in iOS 9.0 - UIAlertView is deprecated. Use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert instead」.orm
說明UIAlertView首先在iOS9中被棄用(不推薦)使用。讓咱們去用UIAlertController。可是運行程序,發現代碼仍是能夠成功運行,不會出現crash。對象
。事件
可是在實際的工程開發中,咱們有這樣一個「潛規則」:要把每個警告(warning)當作錯誤(error)。因此爲了順應蘋果的潮流,咱們來解決這個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
這樣,代碼就不會有警告了。
rem
程序運行後的效果同上。 其中preferredStyle這個參數還有另外一個選擇:UIAlertControllerStyleActionSheet。選擇這個枚舉類型後,實現效果get
發現這個提示框是從底部彈出的。是否是很簡單呢?經過查看代碼還能夠發現,在提示框中的按鈕響應再也不須要delegate委託來實現了。直接使用addAction就能夠在一個block中實現按鈕點擊,很是方便。
總結,能夠發現這裏咱們呈現一個對話框使用了presentViewController這個方法,這個方法是呈現模態視圖(Modal View)的方法,也就是是說,此時的提示框是一個模態視圖。當咱們在進行界面跳轉的時候,也通常使用這個方法,此時呈現的第二個ViewController也是一個模態視圖。咱們能夠把模態視圖理解爲一個浮動在原先視圖上的一個臨時性的視圖或者界面,當在模態視圖中調用dismissViewController方法時,會返回上一個界面,並銷燬這個模態視圖對象。