如何基于布尔(SwiftUI)更改对象的绑定源?

我有一个ObservedObject,我根据来自表单TextFields的用户输入将值传递到其中。但是,我希望用户可以选择使用CoreLocation。当他们更改切换时,我希望TextFields之一的输入值切换到我的CoreLocation发布者。以下是代码段:

@EnvironmentObject var locationmanager: Locationmanager
@ObservedObject var calculator: CalculatorObject
@State var useGPS: Bool = false

if self.useGPS {
   //I'm not sure what to put here
   //I’ve tried several options to set the binding element of the
   //   CalculatorObject to the speed object of the
   //   locationmanager but they don’t change the values within
   //   the calculations. 
}

var body: Some View {
    VStack {
       Toggle(isOn: $useGPS) {
          Text("Use GPS for Ground Speed")
       }

       if useGPS {
          Text(locationmanager.locationInfo.speed)
       } else {
          TextField("Ground Speed",text: self.$calculator.groundSpeed)
       }
    }
}

我尝试了许多不同的选项,但是我似乎无法从位置管理器获取数据以将其数据传递到CalculatorObject.,我已经验证了在更改切换开关时,UI 显示更改的速度,因此我确定位置发布程序正在运行。我不清楚如何更改绑定源。

Jack2090 回答:如何基于布尔(SwiftUI)更改对象的绑定源?

我不确定我是否了解您的目标,但您可能希望遵循以下内容...

   if useGPS {
      TextField("<Other_title_here>",text: self.$calculator.groundSpeed)
          .onAppear {
              self.calculator.groundSpeed = locationManager.locationInfo.speed
          }
   } else {
      TextField("Ground Speed",text: self.$calculator.groundSpeed)
   }
,

@Asperi提供的答案为我指明了正确的方向,但无法与发布者正确合作。这是我最终完成的工作:

   if useGPS {
      TextField("<Other_title_here>",text: self.$calculator.groundSpeed)
           .onReceive(locationManager.objectWillChange,perform: { output in
               self.calculator.groundSpeed = output.speed
           })
   } else {
      TextField("Ground Speed",text: self.$calculator.groundSpeed)
   }

locationManager.objectWillChange函数中使用onReceive发布者正确地订阅了更改。

感谢@Asperi向我指出正确的方向。

本文链接:https://www.f2er.com/2707742.html

大家都在问