UIAlertController के साथ कस्टम डायलॉग/अलर्ट बनाना
Swift में डायलॉग बॉक्स बनाने के लिए हम 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")
// कस्टम एक्शन यहां।
}
- हम एक्शन को अलर्ट में जोड़ेंगे और इसे प्रस्तुत करेंगे।
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")
// कस्टम एक्शन यहां।
}
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.")
}
यह नीचे दिखाए अनुसार परिणाम उत्पन्न करता है:
