Can someone tell me why those are working:
.background(.regularMaterial)
.background(Color(.systemGray5))
But it's not working like this?
.background(colorScheme == .dark ? .regularMaterial : Color(.systemGray5))
CodePudding user response:
There is an overload of background that takes a ShapeStyle, which both Material.regularMaterial and Color conform to.
However, the problem is that the 2 sides of the ternary operator must always have the same type - you cannot have Material on one side and Color on the other side, even though both conform to the same protocol.
You can however create your own @ViewBuilder method, which conditionally calls background with the appropriate value. This way you are always calling background with a concrete type.
extension View {
@ViewBuilder
func myBackground(colorScheme: ColorScheme) -> some View {
if colorScheme == .dark {
background(.regularMaterial)
} else {
background(Color(.systemGray))
}
}
}
Then just call myBackground in your View.
struct ViewWithBackground: View {
@Environment var colorScheme: ColorScheme
var body: some View {
Text("Body")
.myBackground(colorScheme: colorScheme)
}
}
