SwiftUI不能直接调用修改器当自定义Image修改器?

时间:2020-07-01 12:38:16

标签: swiftui

我正在尝试像“文本”修改器一样自定义“图像”修改器:

    struct FlagImage: ViewModifier {
    func body(content: Content) -> some View {
        content
            .renderingMode(.original)
            .clipShape(Capsule())
            .overlay(Capsule().stroke(Color.black, lineWidth: 1))
            .shadow(color: .black, radius: 2)
        }
}

第一个错误是

Value of type 'FlagImage.Content' (aka '_ViewModifier_Content<FlagImage>') has no member 'renderingMode'

Cannot infer contextual base in reference to member 'original'

第二个错误是

Cannot infer contextual base in reference to member 'black'

为什么图像修改器的内容不能直接调用.renderingMode(.original)? 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

ViewModifier是View的修饰符,它是通用视图,因此它的内容在某些通用视图中也是不透明的,您不能对其应用特定的修饰符,例如Image.renderingMode

解决方案是将功能修饰符直接扩展为Image,例如

extension Image {
    func flagImage() -> some View {
        self
            .renderingMode(.original)
            .clipShape(Capsule())
            .overlay(Capsule().stroke(Color.black, lineWidth: 1))
            .shadow(color: .black, radius: 2)
    }
}

通过Xcode 11.4 / iOS 13.4测试