Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use either a Color or LinearGradient in the .foregroundStyle modifier

Tags:

swiftui

I have the following code:

@State var type: String = "color"
@State var color: Color = Color(.black)
@State var gradient: LinearGradient = LinearGradient(colors: [.orange, .red],
                                                         startPoint: .top,
                                                         endPoint: .center)


Text("Hello World!").foregroundStyle(type == "color" ? color : gradient)

It complains that color and gradient aren't the same type. However, there is no conditional logic for modifiers. So, how can I achieve the desired outcome?

Note: I have around 14 other modifiers, so a wrapping if else won't work as some other modifiers have the same issue, so there will be too many if else combinations.

like image 752
Rob Avatar asked Nov 28 '25 19:11

Rob


1 Answers

Wrap the Colour and the LinearGradient in a AnyShapeStyle to achieve type erasure:

@State var type: String = "color"
@State var color: Color = Color(.black)
@State var gradient: LinearGradient = LinearGradient(colors: [.orange, .red],
                                                     startPoint: .top, 
                                                     endPoint: .center)
Text("Hello World!")
    .foregroundStyle(type == "color"
    ? AnyShapeStyle(color) : AnyShapeStyle(gradient))
like image 193
TT-- Avatar answered Nov 30 '25 09:11

TT--



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!