我收到一个错误“Type 'PlayButtonModifier' does not conform to protocol 'ViewModifier'
”,我不明白为什么以及 - 更重要的是 - 如何正确处理。
我只是尝试创建一个 ViewModifier
对于 Image
, 这样我就可以使用 .resizable()
就可以了,只定义在Image
在 ViewModifier
协议(protocol),有一个 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
}
}
同样的错误。
这里有什么问题?怎么会是正确的?
最佳答案
在这种修改特定于特定 View 类型的情况下,Image
比如说,您可以直接在该 View 类型上添加扩展:
extension Image {
func myImageModifier() -> some View {
self
.resizable()
.aspectRatio(1.0, contentMode: .fit)
.clipShape(Circle())
}
}
下面是一个完整的操场文本示例。如果您在名为“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())
关于SwiftUI:内容是图像的 ViewModifier,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58804696/