在從iOS8到iOS9的升級(jí)過程中沪停,彈出提示框的方式有了很大的改變唠倦,在Xcode7 厂镇,iOS9.0的SDK中,已經(jīng)明確提示不再推薦使用UIAlertView雅镊,而只能使用UIAlertController襟雷,我們通過代碼來演示一下。
我通過點(diǎn)擊一個(gè)按鈕仁烹,然后彈出提示框嗤军,代碼示例如下:
#importViewController.h
@interfaceViewController ()
@property(strong,nonatomic) UIButton *button;
@end
@implementationViewController
- (void)viewDidLoad {
[superviewDidLoad];
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];
[alert show];
}
@end
編寫上述代碼時(shí),會(huì)有下列的警告提示:
“‘UIAlertView’ is deprecated:first deprecated in iOS 9.0 - UIAlertView is deprecated. Use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert instead”.
說明UIAlertView首先在iOS9中被棄用(不推薦)使用晃危。讓我們?nèi)ビ肬IAlertController叙赚。但是運(yùn)行程序,發(fā)現(xiàn)代碼還是可以成功運(yùn)行僚饭,不會(huì)出現(xiàn)crash震叮。
但是在實(shí)際的工程開發(fā)中,我們有這樣一個(gè)“潛規(guī)則”:要把每一個(gè)警告(warning)當(dāng)做錯(cuò)誤(error)鳍鸵。所以為了順應(yīng)蘋果的潮流苇瓣,我們來解決這個(gè)warning,使用UIAlertController來解決這個(gè)問題偿乖。代碼如下:
#importViewController.h
@interfaceViewController ()
@property(strong,nonatomic) UIButton *button;
@end
@implementationViewController
- (void)viewDidLoad {
[superviewDidLoad];
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:truecompletion:nil];
}
@end
這樣代碼就不會(huì)有警告了
發(fā)現(xiàn)這個(gè)提示框是從底部彈出的媳禁。是不是很簡(jiǎn)單呢?通過查看代碼還可以發(fā)現(xiàn)画切,在提示框中的按鈕響應(yīng)不再需要delegate委托來實(shí)現(xiàn)了竣稽。直接使用addAction就可以在一個(gè)block中實(shí)現(xiàn)按鈕點(diǎn)擊,非常方便。