返回

iOS Swift Alert 自定义弹窗 点击半透明部分弹窗消失

Android

自定义 UIAlertController 弹窗,使其在点击半透明区域时消失

概述

在 iOS 应用程序中,UIAlertController 是展示信息或提示的强大工具。然而,默认的样式可能并不总能满足您的需求。本文将指导您自定义 UIAlertController 的外观和行为,并使其在点击半透明区域时消失。

创建自定义弹窗

首先,创建一个新的 UIAlertController 实例:

let alertController = UIAlertController(title: "标题", message: "消息", preferredStyle: .alert)
  • title:弹窗标题
  • message:弹窗消息
  • preferredStyle:弹窗样式(可选:.alert、.actionSheet、.custom)

添加按钮

添加按钮以提供交互选项:

alertController.addAction(UIAlertAction(title: "确定", style: .default, handler: { _ in // 确定按钮点击时的处理函数 }))
  • title:按钮标题
  • style:按钮样式(可选:.default、.cancel、.destructive)
  • handler:按钮点击时的处理函数

自定义弹窗外观

您可以自定义弹窗的外观:

  • 标题颜色: alertController.titleTextColor = .blue
  • 消息颜色: alertController.messageTextColor = .black
  • 按钮颜色: alertController.actionTextColor = .red
  • 背景颜色: alertController.backgroundColor = .gray

使其在点击半透明区域时消失

默认情况下,弹窗在点击按钮时消失。要使其在点击半透明区域时消失:

alertController.modalPresentationStyle = .overCurrentContext

显示弹窗

使用 present 方法显示弹窗:

present(alertController, animated: true, completion: nil)

结论

通过本教程,您了解了如何创建自定义 UIAlertController 弹窗,使其在点击半透明区域时消失。此自定义弹窗可以提升用户体验并满足应用程序的特定需求。

常见问题解答

1. 如何使弹窗在屏幕中央显示?

alertController.preferredAction = alertController.actions[1] // 假设第 2 个按钮为 preferredAction

2. 如何隐藏取消按钮?

alertController.actions[1].isVisible = false // 假设第 2 个按钮为取消按钮

3. 如何使弹窗在点击任何地方时消失?

重写 touchesBegan 方法:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    guard let touch = touches.first else { return }
    let point = touch.location(in: self.view)
    if !alertController.view.frame.contains(point) {
        dismiss(animated: true, completion: nil)
    }
}

4. 如何在按钮上添加图像?

使用 image 属性:

alertController.addAction(UIAlertAction(title: "带有图像", style: .default, image: UIImage(named: "image.png"), handler: { _ in // 处理函数 }))

5. 如何设置文本字段?

使用 addTextField 方法:

alertController.addTextField { textField in
    textField.placeholder = "输入文本"
}