iOS UIAlertController Tutorial

Today we're gonna create an app which will show you an alert dialog when the button is pressed using UIAlertController. Let's get started!

What is UIAlertController ?

          UIAlertController class is used to display an alert message to the user. It also have some default actions and styles. 

Creating a Project

  • Open Xcode and Create a new project from the file menu.
  • Select Single View Application template and click Next.
  • Give name to product, organization and organization identifier. See below image for reference.

Adding buttons and making connections

  • Now click the Main.Storyboard file.
  • Drag and drop the Button from the Object Library into the View
  • Now click ctrl and drag from the button to ViewController
  • Then change the connection from Outlet to Action

  • Then name it and click connect.

ViewController Code

 @IBAction func showAlertDialog(_ sender: Any) {
        //Creating alert and enter any string for title and alert messages
        let alert = UIAlertController(title: "Showing alerts", message: "Hey iOS Developers", preferredStyle: UIAlertControllerStyle.alert)
        //Creating actions
        let action = UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: nil)
        //Adding actions to alert
        //After configuring the alert controller with actions. Then present it to ViewController
        present(alert, animated: true, completion: nil)

Run the App

      Now build the project and run it. Then the app will open in Simulator

Now when you click the Show Alert button then it'll show you the alert dialog box.

Finally, we finished and executed the Alert Dialog using UIAlertController class. I hope you understand this tutorial. Share this tutorial if you liked it and feel free to comment if you've any doubts in this tutorial.

Happy Coding :)

Vinoth Vino