如何在 iOS 中点击警报框外部来关闭警报?
iosapps/applicationsmobile development更新于 2026/2/12 5:37:17
理解和实现 UIAlert 可能比较棘手,尤其是对于 iOS 开发新手而言。在本文中,我们将了解如何在用户点击警报框外部时关闭警报。
在本演示中,我们将使用 UIAlert 类来配置警报和操作表,其中包含您想要显示的消息以及可供选择的操作。在配置警报控制器所需的操作和样式后,使用 present(_:animated: completion:) 方法呈现它。 UIKit 会在应用内容上方模态显示警报和操作表。
您可以阅读更多相关信息:https://developer.apple.com/documentation/uikit/uialertcontroller
那么,让我们开始吧!
步骤 1 − 打开 Xcode 并创建一个单视图应用程序,并将其命名为 UIAlertSample。
步骤 2 − 在 Main 中。在 Storyboard 中添加一个按钮,并创建 @IBAction 并将其命名为 showAlert。
@IBAction func showAlert(_ sender: Any) { }
简单来说,当我们点击按钮时,会显示一个提醒;当用户点击提醒外部时,提醒将被关闭。
步骤 3 − 在按钮操作 showAlert 中,首先创建 UIAlert 对象,如下所示
let uialert = UIAlertController(title: "WELCOME", message: "Welcome to my tutorials, tap outside to dismiss the alert", preferredStyle: .alert)
步骤 4 −显示警报并在其完成后添加一个选择器,如下所示:
self.present(uialert, animated: true, completion:{
uialert.view.superview?.isUserInteractionEnabled = true
uialert.view.superview?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.dismissOnTapOutside)))
})
步骤 5 − 添加选择器函数:
@objc func dismissOnTapOutside(){
self.dismiss(animated: true, completion: nil)
}
步骤 6 −运行应用程序,
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func showAlert(_ sender: Any) {
let uialert = UIAlertController(title: "WELCOME", message: "Welcome to my tutorials, tap outside to dismiss the alert", preferredStyle: .alert)
self.present(uialert, animated: true, completion:{
uialert.view.superview?.isUserInteractionEnabled = true
uialert.view.superview?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.dismissOnTapOutside)))
})
}
@objc func dismissOnTapOutside(){
self.dismiss(animated: true, completion: nil)
}
}

