I want define a Color like SwiftUI Primary Color! Right now I am solving my issue with using colorScheme
and also using an if
like in the code:
struct ContentView: View {
var body: some View {
CustomPrimaryView()
.frame(width: 100.0, height: 100.0)
.cornerRadius(10.0)
Color.primary
.frame(width: 100.0, height: 100.0)
.cornerRadius(10.0)
}
}
struct CustomPrimaryView: View {
@Environment(\.colorScheme) var colorScheme
var body: some View {
colorScheme == .light ? Color(red: 0.1, green: 0.1, blue: 0.1) : Color(red: 0.95, green: 0.95, blue: 0.95)
}
}
I would like define a customPrimary Color and access it as Color not as View which dynamically do the job that I am doing in that view. How can we do this in SwiftUI?
CodePudding user response:
What you're talking about is a dynamic color, which chooses its RGB values at the moment it is applied to fill pixels, based on the current appearance traits.
SwiftUI Color
does not (as of 2021) have direct support for creating custom dynamic colors in code. Here are two ways of creating a dynamic Color
.
Asset Catalog
You can create a dynamic color by creating a Color Set in an asset catalog. It looks like this:
Read more about it in Xcode help: Create asset catalogs and sets.
You can then load the color set as a SwiftUI Color
using the Color.init(_ name: String, bundle: Bundle = nil)
initializer. For example:
let myColor = Color("MyColor")
UIColor
You can use UIColor.init(dynamicProvider:)
to create a dynamic UIColor
, then wrap it in a SwiftUI Color
:
let uiColor = UIColor { traits in
if traits.userInterfaceStyle == .dark {
return .init(red: 0.567, green: 0.622, blue: 0.725, alpha: 1)
} else {
return .init(red: 0.204, green: 0.324, blue: 0.374, alpha: 1)
}
}
let color = Color(uiColor: uiColor)
If you're targeting macOS, you can use NSColor.init(name:dynamicProvider:)
.
CodePudding user response:
I assume you wanted something like this
extension Color {
static var customPrimaryColor: Color {
let currentStyle = UIScreen.main.traitCollection.userInterfaceStyle
return currentStyle == .light ? Color(red: 0.1, green: 0.1, blue: 0.1) : Color(red: 0.95, green: 0.95, blue: 0.95)
}
}
and you can use it directly like
var body: some View {
Text("HELLO WORLD!")
.foregroundColor(.customPrimaryColor)
}
and this will be updated automatically on device's color scheme changes
Tested with Xcode 13 / iOS 15