问题在于,单击“增量”会增加“计数”,而不是“嵌套”。有谁知道为什么会这样,并且可能如何解决?还是当SwiftUI视图嵌套在State
变量中时,它们会从根本上中断吗?
struct ContentView: View {
var body: some View {
VStack {
Text("Count: \(count)")
nested
Button(action: {
self.count += 1
self.nested.count += 1
}) { Text("Increment") }
}
}
@State var count = 0
struct Nested: View {
var body: some View {
Text("Nested: \(count)")
}
@State var count = 0
}
@State var nested = Nested()
}
答案 0 :(得分:0)
SwiftUI旨在“嵌套”视图,但是您没有按预期使用它。状态变量用于视图所拥有的数据,而嵌套视图并非(至少,通常不是)通常是视图所拥有的数据,因此它不必是状态变量。
相反,您只能将count
变量作为Nested
视图的参数,并且只要父级中的count
状态变量发生变化,它的主体就会重新呈现:
struct ContentView: View {
var body: some View {
VStack {
Text("Count: \(count)")
Nested(count: count) // pass the count as an init param
Button(action: {
self.count += 1
self.nested.count += 1
}) { Text("Increment") }
}
}
@State var count = 0
struct Nested: View {
var body: some View {
Text("Nested: \(count)")
}
var count: Int
}
}