Swiftui 以模式显示工作表时,@State值不变
我试了很多时间,但我不明白为什么它不起作用 问题是当我点击按钮时,工作表中的新值没有更新。它始终显示在“开始”中设置的相同值Swiftui 以模式显示工作表时,@State值不变,swiftui,Swiftui,我试了很多时间,但我不明白为什么它不起作用 问题是当我点击按钮时,工作表中的新值没有更新。它始终显示在“开始”中设置的相同值 @State var value:String = "empty" @State var explorePageIsEnabled:Bool = false VStack{ Button("tap me"){ value = "the new one"
@State var value:String = "empty"
@State var explorePageIsEnabled:Bool = false
VStack{
Button("tap me"){
value = "the new one"
exploreStatusIsEnabled.toggle()
}
.sheet(isPresented: $exploreStatusIsEnabled, content: {
Text(value)
})
}
部署目标是IOS 14+为文本创建一个单独的结构视图,并使用
绑定
struct SheetView: View {
@Binding var value: String
var body: some View {
Text(value)
}
}
struct ContentView: View {
@State private var value: String = "empty"
@State private var explorePageIsEnabled: Bool = false
var body: some View {
VStack{
Button("tap me"){
value = "the new one"
explorePageIsEnabled.toggle()
}
.sheet(isPresented: $explorePageIsEnabled, content: {
SheetView(value: $value)
})
}
}
}
它起作用了!但是为什么@State在这种情况下不起作用呢?您能解释一下吗?这是因为当您更改任何状态变量的值时,视图会重新创建,状态的值不会更改,因此它会为您提供原始值而不是更新值。@RajaKishan我在问题代码的按钮顶部添加了一个文本(值),然后它就如预期的那样工作了?@Asperi你能解释一下上面的评论吗?@Yodagama这是iOS 14中的工作表创建问题。看起来
工作表(isPresented:content:)
现在是预先创建的,因此对值所做的任何更改都将被忽略。正确的解决方案是使用工作表(项目:内容:)
,这样将根据项目
参数创建工作表。这是否回答了您的问题?