Display an Alert View in iOS8 with Swift

Alert views display an informative alert message to the user. Alert views interrupts the user and requires them to stop what they’re doing to choose an action or dismiss the alert. In this tutorial we will display an alert view when the user clicks a button. We will use Swift as the language of this tutorial, so we need Xcode 6. It can be downloaded from Apple's developer portal.

Open Xcode and create a new Single View Application. For product name, use iOS8SwiftAlertViewTutorial 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 change the width to compact. This will change the view to a iPhone portrait mode. 

Drag a button to the main view and give it a title of "Show Alert".

Select the Assistant Editor and open ViewController.swift. Ctrl and drag from the button to the class and create the  following Action

This will create a stub IBAction function inside the ViewController class.

@IBAction func buttonTapped(sender: AnyObject) {

Note in Swift the sender object is of type AnyObject, this is the equivalent of the id object in Objective-C. Next, implement the buttonTapped function.

@IBAction func buttonTapped(sender: AnyObject) {
  let alertController = UIAlertController(title: "iOScreator", message:
    "Hello, world!", preferredStyle: UIAlertControllerStyle.Alert)
  alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil))
  self.presentViewController(alertController, animated: true, completion: nil)

The alerController constant is assigned an UIAlertControllerObject. Since we will show an Alert View the preferredStyle is set to Alert. The alertController is then presented with a call to oresentViewController. Build an Run the project and press the Show Alert button to display the alert view.

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