How to create different types of alerts and actionsheets in iOS:
To show an alert in iOS, we have UIAlertController class. It is used to create one basic Alert in iOS. It uses iOS system layout theme and doesn’t provide a lot of customization. We will learn how to show an alert in iOS, how to add actions, and how to change its styles.
How to create a basic alert:
For this post, I am creating one UIViewController with one Button in the middle:
Here is the ViewController :
import UIKit
class ViewController: UIViewController {
@IBAction func onTapButton(_ sender: Any) {
let alertController = UIAlertController(title: "Hello", message: "Welcome to our Blog !!", preferredStyle: .alert)
self.present(alertController, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
onTapButton is called if we click on the button.
Here, we are creating one instance of UIAlertController and presenting it. Below is the output:
Note that it will not dismiss the alert if we click on its side.
ActionSheet:
We can give preferredStyle: .actionSheet for an alert. It will open one action sheet from bottom.
Adding actions to the Alert:
We can add actions, called UIAlertAction to the Alert. Actions are buttons that are added to the bottom of an Alert. For example :
import UIKit
class ViewController: UIViewController {
@IBAction func onTapButton(_ sender: Any) {
let alertController = UIAlertController(title: "Hello", message: "Welcome to our Blog !!", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: {(action) -> Void in
print("ok tapped")
})
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: {(action) -> Void in
print("Cancel tapped")
})
let dismissAction = UIAlertAction(title: "Dismiss", style: .destructive, handler: {(action) -> Void in
print("Dismiss tapped")
})
alertController.addAction(okAction)
alertController.addAction(cancelAction)
alertController.addAction(dismissAction)
self.present(alertController, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
We have added three actions here with different styles. For each action, we can have one handler.
It will give the below output:
For an actionSheet, it will look as like below:
Adding a text field:
UIAlertController provides a way to add one text field to it:
alertController.addTextField(configurationHandler: {textField in
textField.placeholder = "Enter your message"
})
We can add more than one Text Field to an Alert. alertController.textFields gives the reference to these text fields.
You might also like:
- How to create a Rounded corner UIView in iOS with Swift 4
- How to update application badge count locally in iOS swift
- How to dismiss a keyboard on tap outside view in iOS swift
- (iOS) Adding Swipe gesture to a view in Swift 4
- Swift program to get the index for a key in Dictionary
- Create a button programmatically in iOS using Swift 4