cs193p – Assignment #1 Task #4


Use color to make your UI look nice. At the very least, your operations buttons must be a different color than your keypad buttons, but otherwise you can use color in whatever way you think looks nice.

Adjust the colors in storyboard:

… that’s actually all to do for the task, to change the colors for the pressed buttons we need to use code. There is no method to change the background color for button states. Extend the button class and change the background color creating an image in the wanted color and use this image as background:

extension UIButton {
    func setBackgroundColor(_ color: UIColor, forState state: UIControlState) {
        let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
        let context = UIGraphicsGetCurrentContext();
        let image = UIGraphicsGetImageFromCurrentImageContext()
        setBackgroundImage(image, for: state);

… use this function when adjusting the layout together with the native method for the foreground color:

private func adjustButtonLayout(for view: UIView, isPortrait: Bool) {
            if let button = subview as? UIButton {
                button.setBackgroundColor(UIColor.black, forState: .highlighted)
                button.setTitleColor(UIColor.white, for: .highlighted)
            } else ...

The complete code for the assignment #1 task #4 is available on GitHub.


Flattr this!

Leave a Reply

Your email address will not be published. Required fields are marked *