binaryPilot84
binaryPilot84

Reputation: 1032

How do I change an object's binding source based on a boolean (SwiftUI)?

I have an ObservedObject that I pass values into based on user inputs from the form's TextFields. However, I want the user to have the option to use CoreLocation. When they change the toggle, I want the input value for one of the TextFields to switch to my CoreLocation publisher. Here are the code snippets:

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

I have tried a number of different options, but I cannot seem to get the data from the location manager to pass it's data to the CalculatorObject. I have verified that when I change the toggle, the UI is showing the changing speed, so I am sure that the location publisher is working. I'm not clear on how to change the binding source here.

Upvotes: 0

Views: 366

Answers (2)

binaryPilot84
binaryPilot84

Reputation: 1032

The answer provided by @Asperi pointed me in the right direction, but didn't work with the publisher correctly. Here is what I did that ended up working:

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

Using the locationManager.objectWillChange publisher within the onReceive function subscribed to the changes correctly.

Thanks to @Asperi for pointing me in the right direction.

Upvotes: 0

Asperi
Asperi

Reputation: 257701

I'm not sure I understood your goal, but probably you expect something like following...

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

Upvotes: 3

Related Questions