swift - 如何根据布尔值 (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正在显示变化速度,所以我确信位置发布者正在工作。我不清楚如何在这里更改绑定源。
解决方案
我不确定我是否理解您的目标,但可能您期望以下内容...
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)
}
推荐阅读
- android - 智能投射到“CredentialsClient!” 不可能跟随教程
- windows - 非 UEFI 主板 INSYDE BIOS 3.6 中的 MBR2GPT.exe 转换
- javascript - Angular *ngIf 不再重复
- javascript - 获取整个屏幕的绝对鼠标位置(在全屏模式下)
- mysql - 通过连接表的多个连接表的总和
- postgresql - Keycloak Docker-compose 不使用 postgres 图像
- c - &(float){0} 作为 float* 参数:这是什么意思?
- java - Spark Job 返回的结果不等于 hive SQL
- javascript - 如何在具有值的对象中用逗号转换单词
- javascript - Typescript 中的异步方法链接(刚刚找到了解决方案)