SwiftUI:ViewModifier,其中内容是图像

jbo*_*boi 18 swift swift-protocols swiftui

我收到一个错误“Type 'PlayButtonModifier' does not conform to protocol 'ViewModifier' ”,我不明白为什么,更重要的是 - 如何正确地做。

我只是尝试创建一个ViewModifierfor an Image,以便我可以.resizable()在它上面使用例如,它仅在Image

ViewModifier协议中,有一个TypealiasforContent定义。我天真的想法是这应该有效:

struct PlayButtonModifier: ViewModifier {
    typealias Content = Image

    func body(content: Content) -> some View {
        content
    }
}
Run Code Online (Sandbox Code Playgroud)

嗯,不。太容易了。结构的隐式类型别名也会发生同样的事情:

struct PlayButtonModifier: ViewModifier {
    func body(content: Image) -> some View {
        content
    }
}
Run Code Online (Sandbox Code Playgroud)

同样的错误。

这里有什么问题?怎么会是正确的?

Dad*_*Dad 16

在这种情况下,修改特定于特定视图类型,Image例如,您可以直接在该视图类型上添加扩展:

extension Image {
    func myImageModifier() -> some View {
        self
            .resizable()
            .aspectRatio(1.0, contentMode: .fit)
            .clipShape(Circle())
   }
}
Run Code Online (Sandbox Code Playgroud)

下面是一个完整的操场文本示例。如果您在名为“Otter.png”的游乐场“资源”文件夹中添加一张可爱的水獭图片,您会得到更漂亮的结果:)

import PlaygroundSupport
import SwiftUI

let image = (UIImage(named: "Otter.png") ?? UIImage(systemName: "exclamationmark.square")!)

struct ContentView: View {
    var body: some View {
        VStack {
            Text("hello world")
            Image(uiImage: image)
                .myImageModifier()
        }
    }
}

extension Image {
    func myImageModifier() -> some View {
        self
            .resizable()
            .aspectRatio(1.0, contentMode: .fit)
            .clipShape(Circle())
    }
}

PlaygroundPage.current.liveView = UIHostingController(rootView: ContentView())
Run Code Online (Sandbox Code Playgroud)


jbo*_*boi 13

感谢与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)
    }
}
Run Code Online (Sandbox Code Playgroud)

使用它很简单:

struct MyImageModifier: ImageModifier {
    func body(image: Image) -> some View {
        image.resizable().scaledToFit()
    }
}

struct MyView: View {
    var body: some View {
        Image(systemName: "play").modifier(MyImageModifier())
    }
}
Run Code Online (Sandbox Code Playgroud)

我不是 100% 满意,因为必须将修饰符定义为返回 some View或返回Image. 这两种情况都有缺点,不能与 SwiftUI 完美集成。

当定义ImageModifier返回 an 时,Image它减少了将图像修改为仅特定于图像的修饰符(实际上resizable())的可能性,当定义它返回时,some View我不能链接ImageModifiers 因为第二个修饰符必须是 a ViewModifier