我收到一个错误“ Type 'PlayButtonModifier' does not conform to protocol 'ViewModifier'
”,但我不理解为什么,并且-更重要的是-如何正确执行。
我只是尝试为ViewModifier
创建一个Image
,这样我就可以在其上使用.resizable()
,它仅在Image
中定义
在ViewModifier
协议中,为Typealias
定义了一个Content
。我幼稚的想法是这应该起作用:
struct PlayButtonModifier: ViewModifier {
typealias Content = Image
func body(content: Content) -> some View {
content
}
}
嗯,不。太容易了。对于隐式结构别名,也会发生同样的事情:
struct PlayButtonModifier: ViewModifier {
func body(content: Image) -> some View {
content
}
}
相同错误。
这里怎么了?怎么会正确?
感谢Asperi的评论和讨论,我最终使用了以下代码段。基本上,它是ViewModifier
的实现,专门用于图像。
protocol ImageModifier {
/// `Body` is derived from `View`
associatedtype Body : View
/// Modify an image by applying any modifications into `some View`
func body(image: Image) -> Self.Body
}
extension Image {
func modifier<M>(_ modifier: M) -> some View where M: ImageModifier {
modifier.body(image: self)
}
}
使用起来很简单:
struct MyImageModifier: ImageModifier {
func body(image: Image) -> some View {
image.resizable().scaledToFit()
}
}
struct MyView: View {
var body: some View {
Image(systemName: "play").modifier(MyImageModifier())
}
}
我不是100%满意的,因为必须定义修饰符以返回some View
或返回Image
。两种情况都有缺点,并且不能与SwiftUI完美集成。
[定义ImageModifier
以返回Image
时,它减少了将图像修改为仅针对图像的修饰符(实际上是resizable()
)的可能性,而当定义为返回some View
时,我无法链接[作为第二个修饰符的C0] s必须为ImageModifier
。