Skip to content

Instantly share code, notes, and snippets.

@gngrwzrd
Created December 27, 2022 03:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gngrwzrd/1af7b8a963a3f4e69265d5c319d8a65b to your computer and use it in GitHub Desktop.
Save gngrwzrd/1af7b8a963a3f4e69265d5c319d8a65b to your computer and use it in GitHub Desktop.
class AppDelegate {
func appDidFinishLaunching() {
//Before the app shows root view controller, check for an override style.
window = UIWindow()
if let override = UserDefaults.standard.bool(forKey: "OverrideStyle") {
//There was an override set, use that otherwise use the system appearance
window?.overrideUserInterfaceStyle = override ? .dark : .light
}
}
}
extension UIColor {
static let foregroundPrimary = UIColor { trait in
//bad color choices but this is to illustrate the UIColor with trait block.
if trait.userInterfaceStyle == .dark {
return UIColor.red
}
return UIColor.blue
}
}
class MyViewController : UIViewController {
let label = UILabel()
let layer = CALayer()
func viewDidLoad() {
super.viewDidLoad()
//This color will automatically change when stlye changes.
label.textColor = UIColor.foregroundPrimary
//layers require CGColor, so they have to be updated on trait change.
layer.backgroundColor = UIColor.foregroundPrimary.cgColor
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
//layer colors don't automatically change, so you need to update in trait collection change.
layer.backgroundColor = UIColor.foregroundPrimary.cgColor
}
func onDark() {
//true assumed to be dark
UserDefaults.standard.set(true, forKey: "OverrideStyle")
window?.overrideUserInterfaceStyle = .dark
}
func onLight() {
//false assume to be light.
UserDefaults.standard.set(false, forKey: "OverrideStyle")
window?.overrideUserInterfaceStyle = .light
}
func onClearStyle() {
//clear to use the system defined appearance.
UserDefaults.standard.removeObject(forKey: "OverrideStyle")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment