0

Does anyone know a correct way to do the following:

I have a view which produces a path and I want to fill it either with a color or with a gradient (which are different types).

For this, I have a enum which I pass to the view from the parent view:

enum FillColor {
  case color(_ color: Color)
  case gradient(color1: Color, color2: Color)
}

Inside a view, I have a path:

 var body: some View {
   GeometryReader { geometry in
     Path { path in
     ...
     }
   }   
}

I then need to switch and do smth like:

switch color {
  case .color(let c):
    path.fill(c)
  case .gradient(let c1, let c2):
    let gradient = ...
    path.fill(gradient)
}

Do I create a variable for a Path? But I need to use GeometryReader as well.

annaoomph
  • 552
  • 1
  • 4
  • 22

1 Answers1

0

So what I did is I encapsulated creating a path into a function and then used it to avoid code repetition.
I pass path as inout parameter in order to be able to mutate it.
Sure it's not the ideal solution though..

GeometryReader { geometry in
  switch color {
  case .color(let c):
    Path { path in createPath(&path, geometry: geometry) }
    .fill(c)
  case .gradient(let c1, let c2):
    let gradient = LinearGradient(...)
    Path { path in createPath(&path, geometry: geometry) }
    .fill(gradient)
  }
}
annaoomph
  • 552
  • 1
  • 4
  • 22