如何配置UIAlertController,使指定按钮点击后不关闭弹窗?
实现点击按钮不关闭UIAlertController的方案
当然可以实现这个需求!不过UIAlertAction的默认行为是点击后自动关闭弹窗,所以我们需要用一些小技巧来绕过这个默认逻辑。下面提供两种可行的方案:
方案一:利用延迟重新弹窗(简单易实现)
这个方法的核心思路是:在按钮的handler里执行完自定义操作后,立即重新present同一个弹窗,抵消系统的自动关闭行为。
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"title" message:@"message" preferredStyle:UIAlertControllerStyleAlert]; // 执行操作且不关闭弹窗的按钮 UIAlertAction *doSomethingAction = [UIAlertAction actionWithTitle:@"Do Something" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { // 这里编写你需要执行的自定义操作 NSLog(@"正在执行自定义操作..."); // 重新弹窗,抵消系统的自动关闭逻辑 dispatch_async(dispatch_get_main_queue(), ^{ [self presentViewController:alert animated:NO completion:nil]; }); }]; // 用于关闭弹窗的按钮 UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"关闭" style:UIAlertActionStyleCancel handler:nil]; [alert addAction:doSomethingAction]; [alert addAction:cancelAction]; [self presentViewController:alert animated:YES completion:nil];
方案二:添加自定义按钮(无闪烁,更优雅)
这种方法直接绕过UIAlertAction,给UIAlertController的view添加自定义UIButton,点击时完全由我们控制逻辑,不会触发系统的自动dismiss。
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"title" message:@"message" preferredStyle:UIAlertControllerStyleAlert]; // 添加默认的关闭按钮 UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"关闭" style:UIAlertActionStyleCancel handler:nil]; [alert addAction:cancelAction]; // 创建自定义按钮并设置样式 UIButton *customButton = [[UIButton alloc] initWithFrame:CGRectMake(16, alert.view.frame.size.height - 60, alert.view.frame.size.width - 32, 44)]; [customButton setTitle:@"Do Something" forState:UIControlStateNormal]; [customButton setTitleColor:[UIColor systemBlueColor] forState:UIControlStateNormal]; [customButton addTarget:self action:@selector(handleCustomAction:) forControlEvents:UIControlEventTouchUpInside]; // 将自定义按钮添加到弹窗视图中 [alert.view addSubview:customButton]; [self presentViewController:alert animated:YES completion:nil];
对应的自定义操作方法:
- (void)handleCustomAction:(UIButton *)sender { // 这里编写你需要执行的自定义操作 NSLog(@"执行自定义操作,弹窗保持显示状态"); }
小提示
- 方案一实现最快,仅有的轻微闪烁在多数场景下可以忽略;
- 方案二更美观,但需要注意自定义按钮的布局适配,可根据弹窗视图的实际尺寸动态调整按钮位置;
- 苹果官方并未提供直接让UIAlertAction不关闭弹窗的API,以上都是基于现有API的变通方案,后续系统版本更新可能需要微调实现逻辑。
内容的提问来源于stack exchange,提问作者Luda
相关产品推荐
相关产品推荐

