Stop Hard-Coding Colors in iOS Apps

Photo by Jonatan Pie on Unsplash

Prerequisites:

You will be expected to be aware how to make a Single View Application in Swift.

Terminology

Dark mode: A darker color visual palette for users

The Approach

Light and dark mode puts your app at the mercy of users. They can easily change the look and feel of the app. So how can you make sure that you App will be prepared for this brave new world? There is just one way of doing this:

  • systemGroupedBackground
  • systemBlue
  • systemBackground
  • secondarySystemBackground
  • tertiarySystemBackground
  • Secondary
  • Tertiary
  • Quaternary

Designing for Dark Mode

  • Use UIKit colors and controls
  • Customize colors and images where necessary
  • Decide on the color and appearance of the App

Switching to dark mode in the Storyboard

Still using the Storyboard? We can view a dark or light interface style! The requisite option is highlighted below

Switching to dark mode dynamically in Xcode

From iOS13 we have had a rather attractive Environment Overrides button, and can switch between dark and light mode in real time.

Dynamic images

I’ve noticed that my image doesn’t really match the light mode. Xcode has me covered here, and can switch the image according to the light or dark mode.

let image = UIImage(named: "photo")let asset = image?.imageAssetlet resolvedImage = asset?.image(with: traitCollection)

Make your own dynamic colors

In Xcode you can add your own color set in the asset catalog. The colors can also be written in code!

let myColor = UIColor { (traitCollection: UITraitCollection) -> UIColor in
if traitCollection.userInterfaceStyle == .dark {
return .black
} else {
return .white
}
}
print (myColor.cgColor.components)
// 1let traitCollection = view.traitCollectionlet resolvedColor = myColor.resolvedColor(with: traitCollection
// 2traitCollection.performAsCurrent {    // set border color, or similar Core Graphics color}
// 3UITraitCollection.current = traitCollection// set border color, or similar Core Graphics color
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) {
// reset dynamic colors
}
}

Make your whole App light or dark mode

You can set, in the info.plist, UIUserInterfaceStyle to either light or dark.

Conclusion

Dark Mode has been around for a while, and users expect this. Therefore you should be implementing this in your own applications to give uses that choice and flexibility.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store