ในการสร้างกล่องโต้ตอบอย่างรวดเร็ว เราจะใช้ประโยชน์จาก UIAlertController ซึ่งเป็นส่วนสำคัญของ UIKit เราจะดำเนินการนี้โดยใช้แอปพลิเคชัน iOS และโครงการตัวอย่าง
ก่อนอื่น เราจะสร้างโปรเจ็กต์ว่าง จากนั้นเราจะดำเนินการต่อไปนี้ในตัวควบคุมมุมมองเริ่มต้น
เราจะสร้างวัตถุ UIAlertController
let alert = UIAlertController.init(title: title, message: description, preferredStyle: .alert)
เราจะสร้างการกระทำ
let okAction = UIAlertAction.init(title: "Ok", style: .default) { _ in
print("You tapped ok")
//custom action here.
} เราจะเพิ่มการดำเนินการในการแจ้งเตือนและนำเสนอ
alert.addAction(okAction) self.present(alert, animated: true, completion: nil)
ตอนนี้เราจะแปลงเป็นฟังก์ชัน -
func createAlert(withTitle title:String,andDescription description: String) {
let alert = UIAlertController.init(title: title, message: description, preferredStyle: .alert)
let okAction = UIAlertAction.init(title: "Ok", style: .default) {
_ in print("You tapped ok")
//custom action here.
}
alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)
} ตอนนี้เราจะเรียกฟังก์ชันนี้ในเมธอด viewWillLayoutSubviews ของเรา และนี่คือลักษณะที่ปรากฏเมื่อเราเรียกใช้ฟังก์ชันนี้บนอุปกรณ์
override func viewWillLayoutSubviews() {
self.createAlert(withTitle: "This is an alert", andDescription: "Enter your description here.")
} จะได้ผลลัพธ์ดังรูปด้านล่าง
