Day 2
Adding buttons and actions
How to add a button to the app?
Open Main.Storyboard -> Utilities Panel -> Object Library -> Drag button to the controller
ViewController
A view controller manages a single screen or a portion of a screen. In this app, we have only one screen so only one view controller. View Controller has two parts:
- Main.Storyboard where we add all the UI components to the view
- ViewController.swift where we write code to handle those components
Adding action to the button
Open ViewController.Swift and add a function showAlert() with @IBAction prefix currently printing “Hello World!”. Then go back to Main.storyboard and click on the ViewController in the navigation area. Click on the button “Click Me”. Hold the button down and take the cursor to the ViewController. A drop-down will show with the method showAlert(), select that method. Now the button is connected to the action. When we run the app and click on the button “Hello World” is printed in the console.
Display Popup on clicking the button
Right now I just added the following code instead on print statement in the showAlert() method. We are going to learn what each statement means in the coming lessons.
let alert = UIAlertController(title: "Hello World!", message: "This is my first app", preferredStyle: .alert) let action = UIAlertAction(title: "Awesome", style: .default, handler: nil) alert.addAction(action) present(alert, animated: true, completion: nil)
Now when I run the app and click on the button a pop up appears on the screen.
This is the screenshot of the assignment about adding another button –