UI基础 - UIAlertController

■ 简言

1. UIAlertController 是 iOS 8 推出的新概念, 同时替代了 UIAlertView 和 UIActionSheet,它从系统层级上统一了 alert 的概念,即以 modal 方式或 popover 方式展示

2. 不管是要用 alert 还是 action sheet,都要以 title 和 message 参数来初始化:alert 会在当前显示的 ViewController 中心以模态形式出现,它可以同时拥有按钮和输入框;action sheet 则会在底部滑出,它仅支持按钮

■ 使用方式

1. 基本使用

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"你想干什么?" message:@"我!不!!要!!!" preferredStyle:UIAlertControllerStyleAlert ];
    [self presentViewController:alertController animated:YES completion:nil];
}

运行效果

2. UIAlertController 可添加文本框

 1 - (void)viewDidAppear:(BOOL)animated{
 2     
 3     self.view.backgroundColor = [UIColor cyanColor];
 4     UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"你想做什么 ?" message:@"我不要 " preferredStyle:UIAlertControllerStyleAlert ];
 5     // 添加文本框添:只能使用 UIAlertControllerStyleAlert 样式;如果是 UIAlertControllerStyleActionSheet 则运行崩溃
 6     [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
 7         
 8         textField.secureTextEntry = YES;// 密文
 9         textField.placeholder = @"文本框 A";// 占位符
10         // 动态地监听文本内容
11         [textField addTarget:self action:@selector(textFieldsValueDidChange:) forControlEvents:UIControlEventEditingChanged];
12         
13     }];
14     
15     [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
16         textField.text = @"文本框 B";
17     }];
18     
19     UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"小黑屋" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
20         NSLog(@"%@",[alertController.textFields.firstObject text]);
21     }];
22     [alertController addAction:okAction];
23     UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"凑不要脸" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
24      
25     }];
26     [alertController addAction:cancelAction];
27     
28     // 展示
29     [self presentViewController:alertController animated:YES completion:nil];
30     
31 }
32 
33 -(void)textFieldsValueDidChange:(UITextField*)textField{
34     
35     NSLog(@"%@",textField.text);
36     
37 }

运行效果

 

posted on 2018-04-09 18:59  低头捡石頭  阅读(255)  评论(0编辑  收藏  举报

导航