In this article, we will create an Alert Box with an OK Button. Also, in the end, I’ll provide the code to create an alert box with OK and Cancel buttons. So, let’s get started.
- Open XCode and create a New XCode Project.
- Select iOS-> Single View App and Click Next.
- Name your project and select the language as Swift. Click Next. choose a desired location to save your project and click Create.
- On the left panel, you can see all the files associated with your project. Open Main.storyboard. Here, we will create our UI.
- In the Object Library, you will get all the tools to design your UI. Just type the tool name you need at the bottom, and when it appears in the Object Library, drag and drop it in your View Controller.
- I have created a button in my UI. I want an alert message to be displayed on the button-click.
- You can change the Background color, Text color, Font size, etc as per your requirements in the Attributes Inspector. You can also rename your tool by double-clicking on it.
- For the next step, you need to open the Assistant Editor. On the right-hand side of your screen, on the top, you may see an icon with two circles overlapping each other. That’s your Assistant Editor. On clicking on it, you will be able to open the View Controller of your project.
- To connect your button to the View Controller, drag your mouse from your Button towards the View Controller along with the ‘Ctrl’ button pressed. You will see a blue line while dragging your mouse from your button.
- When you release your mouse, a box appears. Enter the data as shown in the below figure and then press Connect. You can give any name to your button.
For the Alert Box to display, paste the following code inside the Action block of your button.
- let alertController = UIAlertController(title: "Alert", message: "Button clicked!", preferredStyle: .alert)
- let OKAction = UIAlertAction(title: "OK", style: .default) {
- (action: UIAlertAction!) in
-
- print("Ok button tapped");
- }
- alertController.addAction(OKAction)
- self.present(alertController, animated: true, completion: nil)
- Now we are ready to run our project. Run your project in the simulator/iPhone device. On clicking on the button, an alert box must display in the similar manner.
Code to display Alert Box with OK and Cancel Buttons,
- let alertController = UIAlertController(title: "Alert title", message: "Message to display", preferredStyle: .alert)
-
- let OKAction = UIAlertAction(title: "OK", style: .default) {
- (action: UIAlertAction!) in
-
- print("Ok button tapped");
- }
- alertController.addAction(OKAction)
-
- let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) {
- (action: UIAlertAction!) in print("Cancel button tapped");
- }
- alertController.addAction(cancelAction)
-
- self.present(alertController, animated: true, completion: nil)