我试图将目标 View 结构传递到另一个 View ,但代码无法编译。
我想传递一些符合 View 协议(protocol)的结构,因此它可以在导航按钮目的地中使用,但我似乎无法编译它。我也尝试将目的地类型设置为 _View 。非常感谢任何建议。
struct AnimatingCard : View {
var title, subtitle : String
var color : Color
var destination : View
init(title : String, subtitle: String, color: Color, destination : View){
self.title = title
self.subtitle = subtitle
self.color = color
self.destination = destination
}
var body: some View {
NavigationButton(destination: destination) {
...
}
}
}
最佳答案
如果destination
中使用的所有 View 没有共同的具体类型将会是,您应该使用 AnyView
struct 以获得类型删除的混凝土 View
符合对象。
预计到达时间:
AnyView
有一个声明为 init<V>(_ view: V) where V : View
的初始值设定项,所以无论您在哪里创建 AnimatingCard
在你现在应该写之前:
AnimatingCard(title: title, subtitle: subtitle, color: color, destination: AnyView(view))
或者,您可以制作 AnimatingCard
的初始化程序对所有View
通用- 符合类型并执行 AnyView
初始化程序内的转换,如下所示:
init<V>(title : String, subtitle: String, color: Color, destination : V) where V: View {
self.title = title
self.subtitle = subtitle
self.color = color
self.destination = AnyView(destination)
}
关于ios - 协议(protocol) 'View' 只能用作通用约束,因为它具有 Self 或关联类型要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56639069/