I would like to create a View with a shape such as a Rectangle, which is either filled with a linear or an angular gradient, based on a variable.
My attempt looks like this:
struct TempTestView: View {
@State var circleMode: Bool = true
let gradient: Gradient = Gradient(colors: [.red, .green])
var body: some View {
Rectangle()
.fill(circleMode ? AngularGradient(gradient: gradient, center: .center) : LinearGradient(gradient: gradient, startPoint: .leading, endPoint: .trailing))
.opacity(0.5)
.frame(width: 200, height: 200)
}
}
struct TempTestView_Previews: PreviewProvider {
static var previews: some View {
TempTestView()
}
}
Swift throws me an error:
Cannot convert value of type 'AngularGradient' to expected argument type 'FillStyle'
If I change the code to remove the inline if and replace it with either AngularGradient(gradient: gradient, center: .center) or LinearGradient(gradient: gradient, startPoint: .leading, endPoint: .trailing), swift compiles successfully.
If I try to wrap everything in a function that returns some ShapeStyle, swift complains that AngularGradient and LinearGradient are not of the same type. With a View I'd wrap both in AnyView, but I don't see an AnyStyle to wrap in.
My example is simplified. For animation/transition reasons, there cannot be two separate rectangle, which was why I'm looking for an inline solution like in my example.
Any help would be appreciated.