【问题标题】:Setting a @State var from another view in SwiftUI在 SwiftUI 中从另一个视图设置 @State 变量
【发布时间】:2020-04-21 03:10:07
【问题描述】:

我正在尝试从 struct B 的 var b 的 var a 的 struct a 中设置 @State var 的值,但它不起作用。我需要使用@State var,因为我将它作为绑定传递。例如:

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 未设置为"???"。为什么?

【问题讨论】:

标签: swiftui state


【解决方案1】:

您需要使用@Binding 来实现这一点。这是一些示例代码。我让 View B 出现在 View A 里面,这样你就可以直接在屏幕上看到工作结果:

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")
    }
  }
}

【讨论】:

    猜你喜欢
    • 2020-11-22
    • 2020-09-14
    • 2021-08-06
    • 1970-01-01
    • 1970-01-01
    • 2020-06-21
    • 2022-01-15
    • 2019-11-10
    • 2021-10-05
    相关资源
    最近更新 更多