DISCLAIMER: This post is older than one year and maybe out of date.
Display an Alert or Action Sheet Using Swift in iOS 8

Display an Alert or Action Sheet Using Swift in iOS 8

In this example I will show you how to make an alert appear in a Swift based iOS application. Very straight forward and something you are going to need at some point. For this example I will make an alert appear showing the text entered as the message along with two possible actions, one clears the text and the other is a simple cancel button.

First, I created a new single view application, I added text entry and button controls to the screen also creating an @IBOutlet and @IBAction for both controls.

02 - Storyboard with outlet and action.

The alert view and action sheet both use the UIAlertController class, the class will provide you an instance that you use to present your alert. So let’s create an instance when the user touches the button.

There are some straightforward arguments to complete of which the first one speaks for it’s self. The second is the message, I simply assign the current value of the text entry field and the third is the style we want in this case .Alert.

Now we need to add any actions that we want to the alert view (or action sheet!), these would normally be buttons, so we create instances of the UIAlertAction class and use the addAction: method to strangely enough add them! The first action will simply do nothing which makes the alert disappear, the second will clear the contents of the text entry field.

The final stage in preparing the alert is to add the actions to the alert.

Then finally, we need to present the alert view as the last part of the code when the button is touched. We do this by telling the current viewController self to present it.

So the entire contents of the button action should look like this

03 - Storyboard and complete code

Now run the application and enter some text and touch the button, you should see the sheet appear with the two possible options.

04 - iOS Simulator - iPhone 6 - Alert Sheet

Try a button then the other.

Hopefully this short introduction to displaying an alert has given you everything you need to get started, as with everything iOS there are many ways and many uses for things, play around and see what you can come up with.