How do you bind a Color to .fill()?

Viewed 681

I want to bind a color to fill.

.fill($color) // Instance method 'fill(_:style:)' requires that 'Binding<Color>' conform to 'ShapeStyle'

Do I need to create a custom Binding or something? I know I can do a ternary operation on a bound Bool and choose between two colors.. But I want to bind directly to Color.

4 Answers

Either your color is a @State or @Binding you can just use

.fill(color)

binding itself is performed automatically by SwiftUI engine - it detects used corresponding properties in body and refresh body whenever those properties changed.

So I found the answer in Japanese on this persons Blog.

.fill($color.wrappedValue)

It may be a good idea to create a Color Set asset in Xcode for custom colors. You can name the color and use the color name in this way to create a fill:

Rectangle().fill(Color("FreshOrange"))

Screenshot of Xcode color set asset

Could you make sure that you didn't create a custom struct or class which is also named as Color?

If you accidentally use Color as a name for your own data types, then you can get a similar error which you've described.

For example, if you add the following struct, the project can still compile:

struct Color {
    var red: Float
    var green: Float
    var blue: Float
}

But when you would try to use it as a fill color, eg.:

.fill(Color(red: 0.0, green: 0.0, blue: 0.0)

Then you would get the following error:

Instance method 'fill(_:style:)' requires that 'Color' conform to 'ShapeStyle'
Related