0

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!

Ryan
  • 107
  • 7
  • 30
  • Does this answer your question? [How can I check whether dark mode is enabled in iOS/iPadOS?](https://stackoverflow.com/questions/56435720/how-can-i-check-whether-dark-mode-is-enabled-in-ios-ipados) –  Oct 31 '20 at 02:15
  • Marking this as duplicate - see the second code snippet in https://stackoverflow.com/questions/56435720/how-can-i-check-whether-dark-mode-is-enabled-in-ios-ipados - I'll gladly remove my dup vote if you are asking something different. (1) I'm not seeing a check on `.userInterfaceStyle` in your code. (2) There should be no need to call `layoutSubviews`, just change what you need for light/dark and let the OS do the work. –  Oct 31 '20 at 02:18
  • that does not help. The check is on the color. How do you reset the views so the background color is re-applied? – Ryan Oct 31 '20 at 02:34
  • Maybe I'm still not understanding..... the check is on the color? That's not light or dark - it's something else? If so, than why did you state "dark mode colors" and are looking at trait collections? Please, be more specific. Give an better example, one that can be repeated. –  Oct 31 '20 at 04:32

1 Answers1

3

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.

Frank Rupprecht
  • 9,191
  • 31
  • 56