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   低头捡石頭  阅读(278)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示