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 8.2.1 and built for iOS 10.2.

Open Xcode and create a new Single View Application.

For product name, use IOS10DisplayAlertTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.

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".

Button-Autolayout.png

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: UIAlertControllerStyle.alert)
    alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default,handler: nil))
        
    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 IOS10DisplayAlertTutorial at the ioscreator repository on github.