Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> iOS

วิธีปิด Alert เมื่อแตะนอกพื้นที่ Alert ใน iOS

UIAlertController ปิดเมื่อแตะนอก Alert ได้โดยเพิ่ม Gesture Recognizer

อ่านรายละเอียด

ขั้นตอนที่ 1: สร้างโปรเจกต์

Xcode → Single View Application → ชื่อ "UIAlertSample"

ขั้นตอนที่ 2: เพิ่มปุ่มและ IBAction

Main.storyboard: ปุ่ม @IBAction showAlert

ขั้นตอนที่ 3-6: โค้ด ViewController.swift

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)
}
}