我有一个包含整数数组的父视图(内容视图)
父级内部的视图切换器功能根据数组中整数的值切换子级视图。
我遇到的问题是重新呈现了“ view1”(在之前呈现之后),该视图没有重绘,并且文本字段中的文本仍然填充。
如何在每次调用switch函数时重绘子视图?
谢谢
struct ContentView: View {
var views = [2,1,1]
@State var currentView = 0
var body: some View {
VStack{
viewSwitcher()
}
}
func viewSwitcher() -> AnyView {
switch views[currentView] {
case 1:
return AnyView(view1(currentView: self.$currentView))
case 2:
return AnyView(view2(currentView: self.$currentView))
default:
return AnyView(EmptyView())
}
}
}
struct view1:View {
@State var textInput: String = ""
@Binding var currentView: Int
var body: some View {
VStack{
Text("View 1")
TextField("Enter Text", text: self.$textInput)
Button(action: {
self.currentView += 1
}){
Text("Submit")
}
}
}
}
struct view2:View {
@Binding var currentView: Int
var body: some View {
VStack{
Text("View 2")
Button(action: {
self.currentView += 1
}){
Text("Submit")
}
}
}
}
答案 0 :(得分:0)
这是可能的解决方案。使用.id修饰符可使视图每次更新唯一,因此可以重建。
通过Xcode 11.4 / iOS 13.4测试
func viewSwitcher() -> AnyView {
switch views[currentView] {
case 1:
return AnyView(view1(currentView: self.$currentView).id(UUID()))
case 2:
return AnyView(view2(currentView: self.$currentView).id(UUID()))
default:
return AnyView(EmptyView())
}
}