Silver Challenge - View Controllers

Here’s how I resolved the Silver Challenge:

import UIKit

class ConversionViewController: UIViewController {
    var randomFloat: CGFloat {
        return CGFloat(Float.random(in: 0.0...1.0))
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        print("ConversionViewController loaded its view.")
    }
    
    override func viewWillAppear(_ animated: Bool) {
        let randomColor = UIColor(red: randomFloat, green: randomFloat, blue: randomFloat, alpha: 1.0)
        view.backgroundColor = randomColor
    }
}

Basically, I used the UIColor initializer that lets you use floats for the red, green and blue colors and passed them a random float between 0.0 and 1.0 (inclusive). The alpha parameter (the color’s opacity) is set to 1.0 so that it would always be visible. To create the random float, I used a computed property of type CGFloat (as that is what the UIColor initializer requires for its values) so it would be a different CGFloat each time the randomFloat property was accessed. Finally, I set the view’s background to the generated random color.

Edit: Looks like I could’ve also used CGFloat.random() directly to avoid casting the Float to a CGFloat in my computed property. Oh well…

In your code are the red, green and blue components equal? I used a separate random value for each:

override func viewWillAppear(_: Bool) {
    super.viewWillAppear(true)
    
    let red = CGFloat(Float(arc4random()) / (Float(UINT32_MAX)))
    let blue = CGFloat(Float(arc4random()) / (Float(UINT32_MAX)))
    let green = CGFloat(Float(arc4random()) / (Float(UINT32_MAX)))
    
    print(red, blue, green)
    
    view.backgroundColor = UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}

Hi. No, it’s a different value each time the computed property randomFloat is accessed (once for red, another time for green and finally once more for blue) in the UIColor initializer.

I decided to use the HSB version of init, which allows me to change only the hue. This felt more intuitive to me:

class ConversionViewController: UIViewController {
    override func viewWillAppear(_ animated: Bool) {
        let hue = CGFloat.random(in: 0...1)
        let backgroundColor = UIColor(hue: hue, saturation: 1.0, brightness: 1.0, alpha: 1.0).cgColor
        view.layer.backgroundColor = backgroundColor
    }
}

Question: I didn’t do a super call in my override. This didn’t seem to make a difference, but maybe I should be calling super? Any thoughts?

Always read the documentation if you are not sure.

UIViewController documentation says:

func viewWillAppear(_ animated: Bool)

Discussion


If you override this method, you must call super at some point in your implementation.

class ConversionViewController: UIViewController {
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear (animated)
        // Customize
        ...
    }
}
2 Likes