iOS 13 system color for UIButton

Viewed 3076

Apple recommends using system colors to adapt apps to light and dark mode automatically, for example:

myLabel.textColor = UIColor.secondaryLabel

Here Apple lists various properties to be used, such as the one in the example above, and system colors for background, placeholder text, and more.

But it doesn't list a property for UIButton elements.

Which property or other method should we use to adapt UIButtons to theme changes?

As of now, I'm doing this:

myButton.tintColor = UIColor.link

which is supposedly for links but is the only "clickable" property I found.

I'm not looking to use something like UIColor.systemRed, rather something like UIColor.systemBackground, which adapts automatically to the current theme.

2 Answers

Use any system colors you like. They are all adaptive. I applied the system gray color to a button's text:

enter image description here

enter image description here

The color changes when we switch between light and dark mode.

I hope you create colored Assets not one by one. You can use this function to tint images as a extension of UIImageView. I also use the same technique for buttons.

func setImageAndColor(image: UIImage, color: UIColor) {
    let templateImage = image.withRenderingMode(.alwaysTemplate)
    self.image = templateImage
    self.tintColor = color
}

In case you want to define all you own colors, I suggest to create a singleton class named Colors:

import UIKit

class Colors {

static let shared = Colors()

var statusBarStyle: UIStatusBarStyle = .lightContent

private init(){}

func setLightColors() {
    statusBarStyle = .darkContent

    yourColor = UIColor( // choose your favorite color
    styleColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 1)//white

    labelColor            = UIColor(red: 15/255, green: 15/255, blue: 15/255, alpha: 1)
    subLabelColor         = UIColor(red: 25/255, green: 25/255, blue: 25/255, alpha: 1)

............ set values for all colors from here.

}
func setDarkColors() {
    statusBarStyle = .lightContent

    yourColor = // choose your favorite color

............
}
// set initial colors
var yourColor:          UIColor = 
}

If somebody is interested in the whole Colors class, text me or comment below.

I access the colors singleton by: Colors.shared.yourColor

Also for first configuration I set in the very first VC the darkmode number (0-Auto; 1-On; 2-Off):

if darkmodeNumber == 0 {
    if traitCollection.userInterfaceStyle == .light {
        print("Light mode")
        Colors.shared.setLightColors()
    } else {
        print("Dark mode")
        Colors.shared.setDarkColors()
    }
} else if darkmodeNumber == 1 {
    Colors.shared.setDarkColors()
} else if modeNumber == 2 {
    Colors.shared.setLightColors()
}
}

The statusbar should then change also the right way.

Related