Your First Swift 4 & iOS 12 App Online Course – Day 8
Day 8
Closures
Currently the score and round increase as soon as we click on “Hit Me” button. But we would like them to increase when we click on “Ok” in the action box.
This can be handled using closures.
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let action = UIAlertAction(title: "Ok", style: .default, handler: {
action in
self.startNewRound()
})
alert.addAction(action)
present(alert, animated: true, completion: nil)
For each button we have to specify a UIAlertAction object which has three parameters: the title of the alert message, sets the style of the alert message and the handler which tells the alert what should happen when a button is pressed. Before it was nil and so nothing was happening.
Now it starts the new round using a closure. The closure is a lot like an inline method with a parameter action.
Initial score 0 and round 1
Click on Hit Me doesn’t change the score and round now
Click on ok changes the score and round
Adding Extra Screens
Adding another screen to show the rules of the game when we click on the info button.
First, we create a new ViewController file. Click on File -> New -> File. Add the name AboutViewController and make it a subclass of UIViewController. Click on next and make sure BullsEye is selected. Then click on finish.
Next, add ViewContoller in main.storyboard. Add a button “close” and a TextView containing the instructions to this ViewController. Make sure the to uncheck the “editable” attribute of the TextView.
Next, we add the transition from first ViewController to the new ViewController using a Segue. Click on the info button + control and link it to the new ViewController. Select present modally.
Next, we need to link close to a method to dismiss the ViewController using an IBAction method close. In the method, we call another method to dismiss to dismiss the ViewController. Then go to main.storyboard file -> click on the new ViewController -> Go to the identity inspector (third tab) and set the class to AboutViewController. And link the button close to the method close.
Initial screen reappears on clicking the close button
Styling the app
Adding images to Assets.xcassets.
1x – old retina devices – 50×50 pixels
2x – high resolution retina displays – 100×100 pixels
3x – super high resolution retina HD screen – 150×150 pixels
To add a background image to the app, we add an ImageView in the first ViewController in the main.storyboard. And make the ImageView full screen. Then we set the image “Background” to this ImageView. Arrange the ImageView to go in the background.