首页 > 解决方案 > 如何根据布尔值 (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正在显示变化速度,所以我确信位置发布者正在工作。我不清楚如何在这里更改绑定源。

标签: swiftswiftuicore-locationcombine

解决方案


我不确定我是否理解您的目标,但可能您期望以下内容...

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

推荐阅读