我收到错误“Type 'PlayButtonModifier' does not conform to protocol 'ViewModifier'
“我不明白为什么,更重要的是,我不明白如何正确地做到这一点。
我只是尝试创建一个ViewModifier
for an Image
,这样我就可以使用例如.resizable()
其上,仅定义于Image
In the ViewModifier
协议,有一个Typealias
for Content
定义的。我天真的想法是这应该有效:
struct PlayButtonModifier: ViewModifier {
typealias Content = Image
func body(content: Content) -> some View {
content
}
}
嗯,不。太容易了。结构的隐式类型别名也会发生同样的情况:
struct PlayButtonModifier: ViewModifier {
func body(content: Image) -> some View {
content
}
}
同样的错误。
这里有什么问题吗?怎样才算正确呢?
在这种情况下,修改特定于特定视图类型,Image
比如说,您可以直接在该视图类型上添加扩展:
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())
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)