Swift: 结构实例未更新视图
Swift: Struct instances not updating view
以下代码经过简化和隔离。它旨在有一个 Text()
视图,显示按钮被单击的次数,以及一个 Button()
以增加文本视图。
问题:点击按钮实际上并没有改变 Text() 视图,它继续显示“1”
struct Temp: View {
@State var h = struct1()
var body: some View {
VStack {
Button(action: {
h.num += 1
}, label: {
Text("CLICK ME")
})
Text(String(h.num))
}
}
}
struct struct1 {
@State var num = 1
}
有趣的是,相同的代码在 swift playgrounds 中有效(显然 Text()
更改为 print()
)。所以,我想知道这是否是 XCode 特定的错误?如果不是,为什么会这样?
从 struct1
中的变量中删除 @State
SwiftUI 包装器仅适用于 SwiftUI View
s,ObservableObject
.
中的 @Published
除外
我没有在任何文档中明确发现这一点,但包装器符合 DynamicProperty
并且您查看了文档,它说
The view gives values to these properties prior to recomputing the view’s body.
所以这意味着如果包装变量不在也是 SwiftUI View
的 struct
中,它将不会获得更新的值,因为它没有 body
.
https://developer.apple.com/documentation/swiftui/dynamicproperty
错误在于它在 Playgrounds 中有效,但 Playground 似乎有一些这样的东西。可能是因为它的合规和运行方式。
以下代码经过简化和隔离。它旨在有一个 Text()
视图,显示按钮被单击的次数,以及一个 Button()
以增加文本视图。
问题:点击按钮实际上并没有改变 Text() 视图,它继续显示“1”
struct Temp: View {
@State var h = struct1()
var body: some View {
VStack {
Button(action: {
h.num += 1
}, label: {
Text("CLICK ME")
})
Text(String(h.num))
}
}
}
struct struct1 {
@State var num = 1
}
有趣的是,相同的代码在 swift playgrounds 中有效(显然 Text()
更改为 print()
)。所以,我想知道这是否是 XCode 特定的错误?如果不是,为什么会这样?
从 struct1
@State
SwiftUI 包装器仅适用于 SwiftUI View
s,ObservableObject
.
@Published
除外
我没有在任何文档中明确发现这一点,但包装器符合 DynamicProperty
并且您查看了文档,它说
The view gives values to these properties prior to recomputing the view’s body.
所以这意味着如果包装变量不在也是 SwiftUI View
的 struct
中,它将不会获得更新的值,因为它没有 body
.
https://developer.apple.com/documentation/swiftui/dynamicproperty
错误在于它在 Playgrounds 中有效,但 Playground 似乎有一些这样的东西。可能是因为它的合规和运行方式。