Stop Hard-Coding Colors in iOS Apps

Photo by Jonatan Pie on Unsplash

Prerequisites:

Terminology

The Approach

Designing for Dark Mode

Switching to dark mode in the Storyboard

Switching to dark mode dynamically in Xcode

Dynamic images

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

Make your own dynamic colors

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

Conclusion

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