我试图将目标视图结构传递给另一个视图,但是代码无法编译。
我想传递一些符合视图协议的结构,以便可以在导航按钮目标中使用它,但是我似乎无法对其进行编译。我也尝试将目标类型也设置为_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) {
...
}
}
}
答案 0 :(得分:3)
如果destination
中使用的所有视图都没有通用的具体类型,则应使用AnyView
结构来获取类型擦除的具体View
符合对象。
ETA:
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)
}