在 SwiftUI 中从另一个视图设置 @State var [英] Setting a @State var from another view in SwiftUI
本文介绍了在 SwiftUI 中从另一个视图设置 @State var的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从 var b<设置结构
A
的 var a
中的 @State
var 的值/code> 的结构 B
,但它不起作用.我需要使用 @State
变量,因为我将它作为绑定传递.例如:
I am trying to set the value of a @State
var in var a
of struct A
from a var b
of struct B
, but it doesn't work. I need to use a @State
var because I am passing it as a binding. Ex:
struct A : View {
@State var myBindableVar = ""
var body : some View {
TextField(self.$myBindableVar) ...
}
}
struct B : View {
@State var a : A
var body : some View {
Button(action: { self.a.myBindableVar = "???" }) { ... }
}
}
当点击按钮时,
myBindableVar
未设置为 "???"
.为什么?
myBindableVar
isn't set to "???"
when the button is tapped. Why?
推荐答案
你需要使用@Binding 来实现这一点.这是一些示例代码.我让 View B 出现在 View A 中,以便您可以直接在屏幕上看到工作结果:
You need to use @Binding to achieve this. Here is some example code. I let View B appear inside View A so that you can directly see the working result on screen:
struct A : View {
@State var myBindableVar = ""
var body : some View {
VStack {
Text(myBindableVar)
Spacer()
B(myBindableVar: $myBindableVar)
}
}
}
struct B : View {
@Binding var myBindableVar : String
var body : some View {
Button(action: { self.myBindableVar = "Text appears" }) {
Text("Press to change")
}
}
}
这篇关于在 SwiftUI 中从另一个视图设置 @State var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文