Swift is an open-source general-purpose programming language created by Apple Inc. to develop iOS applications. The UIAlertView class is an iOS class that shows alert messages with a title, message, and one or more buttons to interact with the user.
Note: The
UIAlertViewclass has been deprecated in favor ofUIAlertControllersince iOS 8.0.
UIAlertView in SwiftTo display a simple alert in Swift, we can create an instance of UIAlertView in the UIViewController class, as shown in the following example:
Button("Show alert") {// Instantiating UIAlertViewlet alert = UIAlertView(title: "Simple Alert", message: "This is an example of a simple alert message.", delegate: MyViewController.self, cancelButtonTitle: "Cancel")alert.addButton(withTitle: "Ok")//Showing the UIAlertViewalert.show()}func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) {if buttonIndex == alertView.cancelButtonIndex {print("Clicked cancel")} else {print("Clicked ok")}}
UIAlertView.UIAlertView and adds message content and buttons to the alert view for user inputs.show() method to display the alert view.alertView() function that takes a UIAlertView object and the index of the button clicked by the user as the parameter list.buttonIndex and executes the code accordingly.Note: Executing the code above will generate a warning stating that
UIAlertViewis deprecated and must be replaced withUIAlertController.
UIAlertController in SwiftThe UIAlertController class was introduced in iOS 8.0 as a replacement for UIAlertView, providing more options to display alert messages relatively easily. An example code for creating a simple alert view using Swift is shown below:
@IBAction func AlertButton(_ sender: Any) {// Instantiating UIAlertControllerlet alertController = UIAlertController(title: "Simple Alert",message: "This is an example of a simple alert message.",preferredStyle: .alert)// Handling OK actionlet okAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) inprint("Clicked OK")}// Handling Cancel actionlet cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action:UIAlertAction!) inprint("Clicked cancel")}// Adding action buttons to the alert controlleralertController.addAction(okAction)alertController.addAction(cancelAction)// Presenting alert controllerself.present(alertController, animated: true, completion:nil)}
AlertButton function binds the user interface to the code implementation to launch the alert view.UIAlertController and adds a title, message, and style to the alert view.UIAlertAction for handling the input performed by the user once the alert view is displayed.The illustration below shows the code’s output on an iPhone 14 Pro simulator with iOS 16.4.
The following illustration shows the output of the code on the console.
Free Resources