I was chatting with one of my Youtube channel followers the other day and he asked me to publish a very simple example of how to prompt a user with a dialog message and a question “Are you sure you want to delete this?“. This dialog window should be presented when user taps on Delete button.
So with this blog post I am sharing with you an example of how to use UIAlertController and present user with a dialog message when they tap on Delete button. The dialog window will display a question “Are you sure you want to delete this?” and two buttons: Cancel and Yes to confirm their intention. If user clicks on Yes button, a delete() function will be called.
So here we go. Below is a short video tutorial and a source code of the ViewController created on video.
UIAlertController. Confirmation Dialog Example in Swift.
Confirmation Dialog Example Source Code in Swift
import UIKit class ViewController: UIViewController { @IBOutlet weak var myTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func deleteButton(_ sender: UIButton) { // Declare Alert message let dialogMessage = UIAlertController(title: "Confirm", message: "Are you sure you want to delete this?", preferredStyle: .alert) // Create OK button with action handler let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in print("Ok button tapped") self.deleteRecord() }) // Create Cancel button with action handlder let cancel = UIAlertAction(title: "Cancel", style: .cancel) { (action) -> Void in print("Cancel button tapped") } //Add OK and Cancel button to dialog message dialogMessage.addAction(ok) dialogMessage.addAction(cancel) // Present dialog message to user self.present(dialogMessage, animated: true, completion: nil) } func deleteRecord() { print("Deleting text now") self.myTextField.text = "" } }
Also, I have an example of UIAlertController which has two buttons on it and a UITextField:
or here is another interesting example of implementing a feature that asks user to confirm their intention to delete a record. The example below also has a video tutorial and source code available:
I hope this is useful for you!
Please comment below if you have questions.
[raw_html_snippet id=”cookbookpagecoursesheader”]