Home>

I want to practice a custom modifier.
I have defined a Custom Modifier named FillDailyCellModifier that I will use for my Rectangle with the following code:
The content is only .fill (Color.pink), but I get an error.

// Code (simplified)
struct FillDailyCellModifier: ViewModifier {
    func body (content: Content)->some View {
        content
            .fill (Color.pink)
}
Value of type 'FillDailyCellModifier.Content' (aka '_ViewModifier_Content<FillDailyCellModifier>') has no member 'fill'
  

If the argument of body is Content->Rectangle and as! Rectangle is added, a different error will be output.

func body (content: Rectangle)->some View {
    content:
        .fill (Color.pink) as! Rectangle
}
Type 'FillDailyCellModifier' does not conform to protocol 'ViewModifier'

How can it work?
please tell me.

  • Answer # 1

    Since fill () is not a standard Modifier that inherits View Protocol but an instance method of Rectangle, you can achieve it by extending it with extension as follows.

    struct ContentView: View {
        var body: some View {
            Rectangle ()
                .FillDailyCellModifier ()
        }
    }
    extension Rectangle {
        func FillDailyCellModifier ()->some View {
            self
                .fill (Color.pink)
        }
    }