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 }
运行效果
分类:
UI章节
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律