Create a Custom Alert Controller in Swift
The below tutorial demonstrates how to create your own customisable alert in swift.
Let’s Start
- Open Xcode and create a new project
2. Enter product name and fill other details
Once you fill all the details then press Next
3. Open Main.storyboard and add two buttons on View controller Scene. These buttons are used to display two types of alert i.e single button and two button alert.
4. Now create button actions to display alert on button press as shown in the picture
5. Add a new file to our project. Right click on project folder and choose new file
Select Cocoa Touch Class from Source and click Next.
Give the class name you want and select subclass of UIViewController, tick on create XIB file and press next. I have named my file RTCustomAlert
This class will handle all Custom Alert logic and user actions.
6. Design the UI of your Custom Alert. In my case, I used XIB and added Constraints to make it responsive.
Create IBOutlets for all the above views, including the container view.
@IBOutlet weak var titleLabel: UILabel!@IBOutlet weak var messageLabel: UILabel!@IBOutlet weak var okButton: UIButton!@IBOutlet weak var cancelButton: UIButton!@IBOutlet weak var statusImageView: UIImageView!@IBOutlet weak var alertView: UIView!
Create IBActions for buttons -
@IBAction func actionOnOkButton(_ sender: Any) {}@IBAction func actionOnCancelButton(_ sender: Any) {}
7. Create init() method in RTCustomAlert class, initialise nib with name and set transition style and presentation
init() {super.init(nibName: "RTCustomAlert", bundle: Bundle(for: RTCustomAlert.self))self.modalPresentationStyle = .overCurrentContextself.modalTransitionStyle = .crossDissolve}required init?(coder: NSCoder) {fatalError("init(coder:) has not been implemented")}
8. Now create func show() and add below code to display alert
func show() {if #available(iOS 13, *) {UIApplication.shared.windows.first?.rootViewController?.present(self, animated: true, completion: nil)} else {UIApplication.shared.keyWindow?.rootViewController!.present(self, animated: true, completion: nil)}}
For dismissing alert add below line of code in button actions i.e actionOnOkButton and actionOnCancelButton
self.dismiss(animated: true, completion: nil)
Let’s check our implementation till now
Open ViewController.swift file and add below code into the single button action
let customAlert = RTCustomAlert()customAlert.show()
Build and Run the app. When you do, you will get following result
You notice that we can not change alert title, message etc and not able to handle button actions in our ViewController then let’s complete that stuff
9. Create some properties in RTCustomAlert.swift class which can be use to set values from ViewController class as shown below
var alertTitle = ""var alertMessage = ""var okButtonTitle = "Ok"var cancelButtonTitle = "Cancel"var alertTag = 0var statusImage = UIImage.init(named: "smiley")var isCancelButtonHidden = false
Now create setupAlert() function and set our properties like
func setupAlert() {titleLabel.text = alertTitlemessageLabel.text = alertMessagestatusImageView.image = statusImageokButton.setTitle(okButtonTitle, for: .normal)cancelButton.setTitle(cancelButtonTitle, for: .normal)cancelButton.isHidden = isCancelButtonHidden}
Call setupAlert function in viewDidLoad
override func viewDidLoad() {super.viewDidLoad()setupAlert()}
10. Create delegates which is used to communicate our CustomAlert with the class
protocol RTCustomAlertDelegate: class {func okButtonPressed(_ alert: RTCustomAlert, alertTag: Int)func cancelButtonPressed(_ alert: RTCustomAlert, alertTag: Int)}
Create delegate property
weak var delegate: RTCustomAlertDelegate?
Pass delegate on alert button click
@IBAction func actionOnOkButton(_ sender: Any) {self.dismiss(animated: true, completion: nil)delegate?.okButtonPressed(self, alertTag: alertTag)}@IBAction func actionOnCancelButton(_ sender: Any) {self.dismiss(animated: true, completion: nil)delegate?.cancelButtonPressed(self, alertTag: alertTag)}
11. Update view controller button actions like below
@IBAction func actionOnSingleButtonAlert(_ sender: Any) {let customAlert = RTCustomAlert()customAlert.alertTitle = "Thank you"customAlert.alertMessage = "Your order successfully done."customAlert.alertTag = 1customAlert.statusImage = UIImage.init(named: "smiley")customAlert.isCancelButtonHidden = truecustomAlert.delegate = selfcustomAlert.show()}@IBAction func actionOnTwoButtonAlert(_ sender: Any) {let customAlert = RTCustomAlert()customAlert.alertTitle = "Logout"customAlert.alertMessage = "Do you want to logout?"customAlert.alertTag = 2customAlert.okButtonTitle = "Yes"customAlert.cancelButtonTitle = "No"customAlert.statusImage = UIImage.init(named: "logout")customAlert.delegate = selfcustomAlert.show()}
12. Add delegate methods to the ViewController to handle CustomAlert button click event.
extension ViewController: RTCustomAlertDelegate {func okButtonPressed(_ alert: RTCustomAlert, alertTag: Int) {if alertTag == 1 {print("Single button alert: Ok button pressed")} else {print("Two button alert: Ok button pressed")}print(alert.alertTitle)}func cancelButtonPressed(_ alert: RTCustomAlert, alertTag: Int) {print("Cancel button pressed")}}
Build and run the app, you will get following result
Its a very simple custom Alert, but with few things in mind you could custom it as you want/need.
Thanks for reading 😊
Code