swiftui - 如何使用 SwiftUI 将视图包装在“状态”属性更新中
问题描述
下面的代码创建了一个简单的代码HStack
,最终看起来像这样:
问题是点击“增量”会增加“计数”而不是“嵌套”。有谁知道为什么会这样,以及如何解决这个问题?State
或者当 SwiftUI 视图嵌套在变量中时,它们是否会从根本上中断?
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()
}
解决方案
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
}
}
推荐阅读
- networking - 仅使用一根以太网电缆设置 VLAN
- bash - Bash,将 glob 分配给变量
- javascript - 节点:将数据从中间件发送到函数
- javascript - 使用 jquery 条纹支付更改数据货币属性
- android - 为什么这个示例应用程序中的存储库类是单例的?
- visual-studio-code - 如何更改 VSCode 上的 JavaScript 缩进?
- django - UploadFileForm(request.POST, request.FILES) 返回 null
- linux - 重启所有服务器不完整的 pgs 时的 Ceph 擦除编码
- javascript - JS从孩子中获取孩子的父母ID
- c# - WPF 应用程序在添加或删除平板设备后停止响应触摸