3

SwiftUI offers theme dependent Colors like .primary and .secondary. How to get inverted versions of these (to use as background for example)? System itself knows which background color to use depending on light/dark theme.

5
  • 1
    The system does it by calling this method: developer.apple.com/documentation/uikit/uicolor/… So can you.
    – matt
    Commented Oct 14, 2021 at 13:53
  • You can create UIColor with needed Color then invert it (using approach like in stackoverflow.com/a/5901586/12299030) then convert back by creating Color with result UIColor.
    – Asperi
    Commented Oct 14, 2021 at 15:15
  • The proper way to invert a color in SwiftUI is to call .colorInvert() on the color. It takes the current color, adjusted for dark mode, etc, and returns its inverse.
    – Yrb
    Commented Oct 14, 2021 at 17:59
  • 1
    .colorInvert() produces some View and cannot be used where Color parameter is expected, @Yrb. Though it is possible for example to use it on a Text to invert its color of course.
    – Paul B
    Commented Oct 14, 2021 at 18:46
  • You had asked specifically about using as a background which takes a view.
    – Yrb
    Commented Oct 14, 2021 at 18:48

1 Answer 1

4

you can use the colors "label" and "systembackground", they are usually opposite.

So use UIColor.systemBackground and UIColor.systemLabel for the opposite

or UIColor.secondarySystemBackground and UIColor.secondarySystemLabel etc...

3
  • @Paul B Is this what you are looking for?
    – Abv
    Commented Oct 14, 2021 at 14:42
  • 3
    I was looking for SwiftUI way of doing this, not UIKit way. But since we can do Color(uiColor: UIColor.systemBackground) in iOS 15 to get the Color bridged to UIColor the suggested solution is a working one, @Abv. There are plenty of theme dependent colors in UIColor.
    – Paul B
    Commented Oct 14, 2021 at 15:35
  • Type 'UIColor' has no member 'systemLabel'
    – Eldar
    Commented Mar 20, 2023 at 17:03

Not the answer you're looking for? Browse other questions tagged or ask your own question.