如何在 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