如何在 SwiftUI 中遵守 ShapeStyle 协议?

How can I conform to ShapeStyle protocol in SwiftUI?

我希望符合 ShapeStyle,目标只是符合 ShapeStyle(仅此而已)。

这是我的代码和问题:

struct MyContentView: View {
    var body: some View {
        Circle()
            .fill(RedView())
    }
}

struct RedView: View {
    var body: some View {
        Color.red
    }
}

所以我知道我可以直接使用 Color.red 而不是视图,但正如我所说,这个问题的目标是符合 ShapeStyle。对于那些要分享苹果开发者 link 关于 ShapeStyle 的人,我不得不说我以前在那里。

错误:

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

来自 ShapeStyle 的文档:

You don’t use the ShapeStyle protocol directly. Instead, use one of the concrete styles that SwiftUI defines. To indicate a specific color or pattern, you can use Color or the style returned by image(_:sourceRect:scale:), or one of the gradient types, like the one returned by radialGradient(_:center:startRadius:endRadius:). To set a color that’s appropriate for a given context on a given platform, use one of the semantic styles, like background or primary.

我相信您可以通过以下方式实现您的目标:

struct MyContentView: View {
    var body: some View {
        Circle()
            .fill(.red)
    }
}

免责声明: 以下仅用于演示,因为所有使用的API都是私有的(按照约定,不是设计),所以反应苹果如果你提交带有这样代码的应用程序到AppStore是不可预测的。

注意:由于使用的接口是私有的,因此可以使用任何新版本进行更改。

主要部分:

  public func _apply(to shape: inout SwiftUI._ShapeStyle_Shape) {
    Color.red._apply(to: &shape)  // << here !!
  }

Xcode 13.3 / iOS 15.4

完成findings and code is here

如果您希望任何类型的视图符合ShapeStyle,那么@Asperi 在这里提供了答案。

如果你想让 Color 像你的例子中那样符合 ShapeStyle,它已经采用了那个协议,所以你只需要稍微调整一下就可以让它工作,就像这样:

struct RedView {
    var render: some ShapeStyle {
        Color.red
    }
}

struct MyContentView: View {
    var body: some View {
        Circle()
            .fill(RedView().render)
    }
}