如何在 iOS 中点击警报外部关闭警报?
理解和实现 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)
}
}
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP