Search code examples
swiftios-darkmode

Swift How can you reset the colors of all the subviews on a page?


How can you automatically reset the colors of all the subviews on a page?

I am defining dark mode colors doing something like this:

    static let textColor: UIColor = UITraitCollection.current.userInterfaceStyle == .light ? .black : .white

If a user has the app open when dark mode automatically takes place (based off a user's settings) then the colors do not change. You have to close the app and re-open it to see dark mode.

How can you automatically reset the colors of all the subviews on a page?

This is what I tried:

 override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    super.traitCollectionDidChange(previousTraitCollection)
    view.layoutSubviews()
    view.subviews.forEach {$0.layoutSubviews()}
}

LayoutSubviews does not reset the color.

Any ideas?

Thanks!


Solution

  • You need to use dynamic colors in order to have them adapt automatically. Here

    UITraitCollection.current.userInterfaceStyle == .light ? .black : .white
    

    you check for the interface style right at that moment and set the color, but that code is not re-evaluated automatically when the trait environment changes.

    Instead, you can use one of the system colors (like .background or .label), which will adapt to dark/light mode changes automatically. If you want to define your own, the easiest way would be using asset catalogs. When you add a color there, you can define how it looks in light and dark mode separately.