Skip to content

Instantly share code, notes, and snippets.

@ytyubox
Last active January 18, 2021 06:49
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ytyubox/c125aafded6d00e398fa42f9cbd0366a to your computer and use it in GitHub Desktop.
Save ytyubox/c125aafded6d00e398fa42f9cbd0366a to your computer and use it in GitHub Desktop.
Dark mode color without xcassets

Auto updateColor

Like setting color in the XCASSETS, but with code and applyable < iOS 12. By Encapsulating the iOS versioning in the AutoUpdateColor, we can have the UIView.color = ... without the color setup.

// ViewController.swift

let themeMainColor = AutoUpdateColor(lightColor: .blue, darkColor: .yellow)

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = themeMainColor
    }
}
import UIKit
class AutoUpdateColor: UIColor {
convenience init(lightColor: UIColor, darkColor: UIColor) {
if #available(iOS 13.0, *) {
self.init {
traitCollection in
traitCollection.userInterfaceStyle == .dark
? darkColor
: lightColor
}
} else {
self.init(cgColor: lightColor.cgColor)
}
}
}
@ytyubox
Copy link
Author

ytyubox commented Jan 7, 2021

The closure feed to UIColor.init can have more conditions on ENV, such as different theme.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment