Display Alert iOS Tutorial

A UIAlertController object displays an alert message to the user. This class replaces the UIActionSheet and UIAlertView classes for displaying alerts. In this tutorial we will display an alert when the user clicks a button. This tutorial is made with Xcode 10 and built for iOS 12.

Open Xcode and create a new Single View App.

For product name, use IOSDisplayAlertTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

Go to the Storyboard and drag a Button to the main View. Double-click the button and give it a title of "Display Alert". Select the button and click the Pin Auto Layout button on the bottom-right of the Storyboard. Pin the button at the top edge and select "Items of New Constraints" at the Update Frames section. Select "Add 1 Constraint".

Select the button and click the Align Auto Layout button. Select the "Horizontally in Container" checkbox and select "Items of New Constraints" at the Update Frames section. Select "Add 1 Constraint".

Select the Assistant Editor and open ViewController.swift. Ctrl-drag or right-click-drag from the Button to the class and create the following Action.

Next, implement the showAlert function.

@IBAction func showAlert(_ sender: Any) {
    let alertController = UIAlertController(title: "iOScreator", message:
        "Hello, world!", preferredStyle: .alert)
    alertController.addAction(UIAlertAction(title: "Dismiss", style: .default))

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

The alertController constant is assigned an UIAlertController object. Since we will show an Alert the preferredStyle is set to alert. The alertController is then presented modally with the present(_:animated:completion:) method. Build and Run the project and press the Display Alert button to display the alert.

You can download the source code of the IOSDisplayAlertTutorial at the ioscreator repository on github.