我正在尝试将目标视图结构传递给另一个视图,但代码无法编译。
我想传入一些符合视图协议的结构,因此它可以用于导航按钮目的地,但我似乎无法编译它。我也尝试将目的地类型设置为 _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) {
...
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果没有所有视图使用的通用具体类型destination
,您应该使用AnyView
结构来获取类型擦除的具体View
符合对象。
预计到达时间:
AnyView
有一个声明为的初始化程序init<V>(_ view: V) where V : View
,所以无论你在哪里创建你AnimatingCard
之前你现在应该写:
AnimatingCard(title: title, subtitle: subtitle, color: color, destination: AnyView(view))
Run Code Online (Sandbox Code Playgroud)
或者,您可以使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)
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3340 次 |
最近记录: |