由于SwiftUI不保存视图对象,因此无法将已初始化的视图对象进行传递:
struct ParentView:View{
var childView:View //Error: Use of protocol 'View' as a type must be written 'any View'
var body: some View{
childView //Error: Type 'any View' cannot conform to 'View'
}
}
可用的一个传递方法:
struct ParentView<ChildView:View>:View{
var childView:() -> ChildView
var body: some View{
childView()
}
}
用法:
ParentView{
Text("我是儿子")
}
网友评论