【问题标题】:How do I define a struct property to accept Linear or Angular gradients in SwiftUI?如何在 SwiftUI 中定义结构属性以接受线性或角度渐变?
【发布时间】:2021-12-30 06:57:08
【问题描述】:

我想创建一个可以接受线性或角度渐变作为属性的视图。虽然两种渐变都符合 ShapeStyle,但我无法用它定义属性类型。

如果视图只接受一个 LinearGradient,则如下所示:

struct NewView: View {
  var fill: LinearGradient

  init(fill: LinearGradient = LinearGradient(gradient: Gradient(colors: [Color.green, Color.blue]), startPoint: .top, endPoint: .bottom) {
    self.fill = fill
  }

  var body: some View {
    Circle()
      .stroke(fill, style: StrokeStyle(lineWidth: 25))
  }
}

理想情况下,它会接受填充属性中的任何一个渐变,而不需要任何其他属性。

【问题讨论】:

    标签: swift swiftui


    【解决方案1】:

    我最终使用了带有两个初始化块的 AnyShapeStyle 类型,如下所示:

    struct NewView: View {
      var fill: AnyShapeStyle
    
      init(fill: LinearGradient = LinearGradient(gradient: Gradient(colors: [Color.green, Color.blue]), startPoint: .top, endPoint: .bottom) {
        self.fill = AnyShapeStyle(fill)
      }
    
    init(fill: AngularGradient = AngularGradient(colors: [.green, .blue], center: .center) {
        self.fill = AnyShapeStyle(fill)
      }
    
      var body: some View {
        Circle()
          .stroke(fill, style: StrokeStyle(lineWidth: 25))
      }
    }
    

    【讨论】:

      【解决方案2】:

      设置ShapeStyle 约束。

      struct NewView<Style: ShapeStyle>: View {
          var fill: Style
          
          init(fill: Style) {
              self.fill = fill
          }
          
          var body: some View {
              Circle()
                  .stroke(fill, style: StrokeStyle(lineWidth: 25))
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-15
        • 2012-03-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-27
        • 1970-01-01
        相关资源
        最近更新 更多