iOS9使用提示框的正確實(shí)現(xiàn)方式
在從iOS8到iOS9的升級(jí)過(guò)程中,彈出提示框的方式有了很大的改變,在Xcode7 ,iOS9.0的SDK中,已經(jīng)明確提示不再推薦使用UIAlertView,而只能使用UIAlertController,我們通過(guò)代碼來(lái)演示一下。
我通過(guò)點(diǎn)擊一個(gè)按鈕,然后彈出提示框,代碼示例如下:
- [objc] view plaincopyprint?
- #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:@"跳轉(zhuǎn)" 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:@"按鈕被點(diǎn)擊了" delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil, nil nil];
- [alert show];
- }
- @end
編寫(xiě)上述代碼時(shí),會(huì)有下列的警告提示:
- “‘UIAlertView’ is deprecated:first deprecated in iOS 9.0 - UIAlertView is deprecated. Use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert instead”.
說(shuō)明UIAlertView首先在iOS9中被棄用(不推薦)使用。讓我們?nèi)ビ肬IAlertController。但是運(yùn)行程序,發(fā)現(xiàn)代碼還是可以成功運(yùn)行,不會(huì)出現(xiàn)crash。
但是在實(shí)際的工程開(kāi)發(fā)中,我們有這樣一個(gè)“潛規(guī)則”:要把每一個(gè)警告(warning)當(dāng)做錯(cuò)誤(error)。所以為了順應(yīng)蘋(píng)果的潮流,我們來(lái)解決這個(gè)warning,使用UIAlertController來(lái)解決這個(gè)問(wèn)題。代碼如下:
- [objc] view plaincopyprint?
- #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:@"跳轉(zhuǎn)" 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:@"按鈕被點(diǎn)擊了" preferredStyle: UIAlertControllerStyleAlert];
- [alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
- //點(diǎn)擊按鈕的響應(yīng)事件;
- }]];
- //彈出提示框;
- [self presentViewController:alert animated:true completion:nil];
- }
- @end
這樣,代碼就不會(huì)有警告了。
程序運(yùn)行后的效果同上。 其中preferredStyle這個(gè)參數(shù)還有另一個(gè)選擇:UIAlertControllerStyleActionSheet。選擇這個(gè)枚舉類(lèi)型后,實(shí)現(xiàn)效果如下:
發(fā)現(xiàn)這個(gè)提示框是從底部彈出的。是不是很簡(jiǎn)單呢?通過(guò)查看代碼還可以發(fā)現(xiàn),在提示框中的按鈕響應(yīng)不再需要delegate委托來(lái)實(shí)現(xiàn)了。直接使用addAction就可以在一個(gè)block中實(shí)現(xiàn)按鈕點(diǎn)擊,非常方便。