如何更改对象';基于布尔值的绑定源(SwiftUI)?
我有一个如何更改对象';基于布尔值的绑定源(SwiftUI)?,swift,swiftui,core-location,combine,Swift,Swiftui,Core Location,Combine,我有一个ObservedObject,我根据表单的TextFields中的用户输入将值传递到该对象中。但是,我希望用户可以选择使用CoreLocation。当他们更改切换时,我希望其中一个TextFields的输入值切换到我的CoreLocationpublisher。以下是代码片段: @EnvironmentObject var locationManager: LocationManager @ObservedObject var calculator: CalculatorObject @
ObservedObject
,我根据表单的TextFields
中的用户输入将值传递到该对象中。但是,我希望用户可以选择使用CoreLocation。当他们更改切换时,我希望其中一个TextFields
的输入值切换到我的CoreLocation
publisher。以下是代码片段:
@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显示了更改速度,因此我确信位置发布器正在工作。我不清楚如何更改这里的绑定源。我不确定我是否理解您的目标,但您可能希望看到以下内容
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)
}
如果使用GPS{
TextField(“,text:self.$calculator.groundSpeed)
奥纳佩尔先生{
self.calculator.groundSpeed=locationManager.locationInfo.speed
}
}否则{
TextField(“地面速度”,文本: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)
}
如果使用GPS{
TextField(“,text:self.$calculator.groundSpeed)
.onReceive(locationManager.objectWillChange,执行:{中的输出
self.calculator.groundSpeed=输出.speed
})
}否则{
TextField(“地面速度”,文本:self.$calculator.groundSpeed)
}
在onReceive
函数中使用locationManager.objectWillChange
publisher以正确订阅更改
感谢@Asperi为我指明了正确的方向