在Xcode7 ,iOS9.0的SDK中昆著,已經(jīng)明確提示不再推薦使用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:@"跳轉(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
但是會有警告‘UIAlertView’ is deprecated:first deprecated in iOS 9.0 - UIAlertView is deprecated.
表明UIAlertView已經(jīng)iOS9中被棄用(不推薦)使用潦刃。推薦使用UIAlertController变隔。
為解決這個(gè)warning,使用UIAlertController來解決這個(gè)問題茵宪。代碼如下:
#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
通過運(yùn)行發(fā)下暖哨,程序運(yùn)行后的效果相同。 其中preferredStyle
這個(gè)參數(shù)還有另一個(gè)選擇:UIAlertControllerStyleActionSheet
凰狞。選擇這個(gè)枚舉類型后篇裁,實(shí)現(xiàn)效果:提示框會從底部彈出。
對比:通過查看代碼還可以發(fā)現(xiàn)赡若,在提示框中的按鈕響應(yīng)不再需要delegate委托來實(shí)現(xiàn)了达布。直接使用addAction
就可以在一個(gè)block中實(shí)現(xiàn)按鈕點(diǎn)擊,非常方便逾冬。