SwiftUI offers theme dependent Color
s 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.
Asked
Active
Viewed 3,163 times
2

Paul B
- 3,989
- 33
- 46
-
1The system does it by calling this method: https://developer.apple.com/documentation/uikit/uicolor/3238042-resolvedcolor So can you. – matt Oct 14 '21 at 13:53
-
You can create `UIColor` with needed `Color` then invert it (using approach like in https://stackoverflow.com/a/5901586/12299030) then convert back by creating `Color` with result `UIColor`. – Asperi Oct 14 '21 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 Oct 14 '21 at 17:59
-
`.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 Oct 14 '21 at 18:46
-
You had asked specifically about using as a background which takes a view. – Yrb Oct 14 '21 at 18:48
1 Answers
1
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...

Abv
- 354
- 2
- 13
-
-
1I 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 Oct 14 '21 at 15:35
-