Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a property to be either Color or LinearGradient in SwiftUI?

I want to store a backColor property to be used for drawing. How can I make this property takes either Color or LinearGradient?

struct Card {
    let backColor: Color
}

let colorBackCard = Card(backColor: Color.red)
let gradientBackCard = Card(backColor: LinearGradient(...))

Last line of code showing: Cannot convert value of type 'LinearGradient' to expected argument type 'Color'.

How can I fix this property?

Thanks

--

I tried this:

enum ColorGradient {
    case color(Color)
    case gradient(LinearGradient)
}

struct Card {
    let backColor: ColorGradient
}

let colorBackCard = Card(backColor: ColorGradient.color(Color.red))
let gradientBackCard = Card(backColor: ColorGradient.gradient(LinearGradient(...)))

But when I use this property to draw in View, it reports:

Instance method 'background(_:alignment:)' requires that 'ColorGradient' conform to 'View'

--

I now use 2 separate variables Color? and LinearGradient?.

like image 420
humanitylegopiece Avatar asked Nov 15 '25 17:11

humanitylegopiece


1 Answers

If you use it directly in view then the following would be more appropriate

struct Card<Background: View> {
    let backColor: Background
}

// no changes in below
let colorBackCard = Card(backColor: Color.red)
let gradientBackCard = Card(backColor: LinearGradient(...))
like image 164
Asperi Avatar answered Nov 17 '25 09:11

Asperi



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!