In this tutorial, we are going to discuss about implementation of Alert controller using Objective-C Language in iOS application in Xcode 8. Alert Controller basically is used to display message as an alert or action.
Alert Controller consists:
In this tutorial, we will discuss ‘Alert’ only and in the next blog we will discuss about ActionSheet.
Following are the steps to implement Alert Controller:
Step 1: Open Xcode -> click on Create new Xcode project then choose Single View Application template under iOS tab as shown in below image and click Next button.
Step 2: Enter the product name as AlertControllerDemo, select the Language as Objective-C and again click Next button as shown in below image. Later click Create button to create project appear on the next window.
Step 3: Adding UIButton to the View Controller.
On your project, click on main.storyboard file available in the project navigator, and then select the UIButton from object library, drag into the superview of View Controller, it will look like below.
Step 4: Declaring IBAction property for Button.
Select the Assistant Editor and create IBAction property for UIButton by holding Ctrl button. It will open up a popup view like below then enter the Name as ‘Show Alert’ and click Connect.
The property IBAction is defined because alert will be displayed on action event of Button where AlertController code is written (as seen in below screenshot).
Step 5: Complete Code in ViewController.m file
In ViewController.m file, code to present Alert is written on action method of button as shown in below screenshot.
Most Importantly, we have two preferredStyle in AlertController as follows:
Hence, we need to choose ‘UIAlertControllerStyleAlert’ for showing Alert.
For adding button into Alert, we need to define button using class ‘UIAlertAction’ and then need to add as subView of Alert.
Lastly, we need to present View Controller. That’s it.
Step 6: Finally, Build and Run the application where you will get the output like below.
Have Fun !
You can also watch its video on below link: