@State属性不按预期更改其值,直到我添加`onChange(of:)
import SwiftUI
struct ContentView: View {
@State private var openSheet = false
@State private var foo = 0
var body: some View {
Button {
setFoo(100)
openSheet = true
} label: {
Text("Open Sheet")
}
.padding()
.frame(width: 400, height: 300, alignment: .center)
.sheet(isPresented: $openSheet) {
Text(String(foo))
.padding()
.frame(width: 200, height: 150, alignment: .center)
}
}
private func setFoo(_ foo:Int) {
self.foo = foo
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
上述代码运行时,结果为“ 0”,而不是“ 100”。但是,如果我添加了“。
import SwiftUI
struct ContentView: View {
@State private var openSheet = false
@State private var foo = 0
var body: some View {
Button {
setFoo(100)
openSheet = true
} label: {
Text("Open Sheet")
}
.padding()
.frame(width: 400, height: 300, alignment: .center)
.sheet(isPresented: $openSheet) {
Text(String(foo))
.padding()
.frame(width: 200, height: 150, alignment: .center)
}
.onChange(of: openSheet) { newValue in
}
}
private func setFoo(_ foo:Int) {
self.foo = foo
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
知道为什么会发生这种情况?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用此处的许多@asperi答案之一:
a>
您可以使用这样的东西:
using one of the many @Asperi answers from here:
Sheet inside ForEach doesn't loop over items SwiftUI
you could use something like this: