Create UIAlertController with OK Button in Swift

In this short Swift code example, we will use the UIAlertController to create an alert dialog message with only one “OK” button.

The code example below will demonstrate how to:

  • Create UIAlertController with a Title and a Message to display,
  • Add a UIAlertAction with the OK label to UIAlertController,
  • Handle UIAlertAction to know when the user taps on the OK button.

If you are interested in video lessons on how to write Unit tests and UI tests to test your Swift mobile app, check out this page: Unit Testing Swift Mobile App

Creating an Alert Dialog Using UIAlertController

let alertController = UIAlertController(title: "Alert title", message: "Message to display", preferredStyle: .alert)

let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in
    
    // Code in this block will trigger when OK button is tapped.
    print("Ok button tapped");
    
}

alertController.addAction(OKAction)

self.present(alertController, animated: true, completion:nil)

For more Swift code examples and tutorials, please check the Swift Code Examples page on this website.


Leave a Reply

Your email address will not be published. Required fields are marked *