我有一个Swift ui视图,其中一个女巫从@State变量获取值。当我更新@State变量时,视图将重建,但子视图保持不变。
struct ContentView: View {
@State var msg: String = ""
var body: some View {
VStack {
Button(action: {
self.msg = "Hallo World"
}, label: { Text("Say Hallo")})
ChildView(msg: msg).padding().background(Color.orange)
Text(msg).padding().background(Color.green)
}.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
struct ChildView: View {
@State var msg: String
var body: some View {
Text(msg)
}
}
答案 0 :(得分:2)
在其中使用@Binding而不是@State。下面提供了修改后的完整快照。经过测试并可以与Xcode 11.2 / iOS 13.2一起使用。
struct ContentView: View {
@State var msg: String = ""
var body: some View {
VStack {
Button(action: {
self.msg = "Hallo World"
}, label: { Text("Say Hallo")})
ChildView(msg: $msg).padding().background(Color.orange)
Text(msg).padding().background(Color.green)
}.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
struct ChildView: View {
@Binding var msg: String
var body: some View {
Text(msg)
}
}
答案 1 :(得分:0)
import SwiftUI
struct ContentView: View {
@State var msg: String = ""
var body: some View {
VStack {
Button(action: {
self.msg += "Hallo World "
}, label: { Text("Say Hallo")})
ChildView(msg: msg).padding().background(Color.orange)
Text(msg).padding().background(Color.green)
}.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
struct ChildView: View {
var msg: String
var body: some View {
Text(msg)
}
}
您的ChildView中不需要任何状态属性包装器。一旦味精更改,SwiftUI就会知道,应根据其值重新加载每个View。
在您的示例中,您通过将初始值包装到其状态属性包装程序中来“修复”了该。 SwiftUI不会重新加载它,因为@State属性包装器意味着该值存储在ChildView外部。 @State属性包装器不属于View状态。相反,一旦@State包装的属性发生更改,SwiftUI将重新评估View的主体计算属性。要“重置” @State属性包装的值,您需要“重新创建”它,这意味着state属性也将重置为其初始值。