【发布时间】:2022-01-03 10:01:00
【问题描述】:
这里的示例代码非常简单。滑块更新双精度值,但不是相反。使用 Combine 如何更新两个或多个滑块?
struct Centimeters {
var value: Double
func updateInches() -> Double {
return value / 2.54
}
}
struct Inches {
var value: Double
func updateCentimeters() -> Double {
return value * 2.54
}
}
class SizeValueModel: ObservableObject {
@Published var centimeters: Centimeters
@Published var inches: Inches
var cancellables = Set<AnyCancellable>()
init() {
self.centimeters = Centimeters(value: 1.0)
self.inches = Inches(value: 0.393701)
$centimeters.sink {
self.inches.value = $0.updateInches()
}.store(in: &cancellables)
// $inches.sink {
// self.centimeters.value = $0.updateCentimeters()
// }.store(in: &cancellables)
}
}
struct ContentView: View {
@StateObject var model = SizeValueModel()
var body: some View {
Slider(value: $model.centimeters.value, in: 0...100, label: {
Text("\(model.centimeters.value)")
})
Slider(value: $model.inches.value, in: 0...39.3701, label: {
Text("\(model.inches.value)")
})
}
}
【问题讨论】:
-
如果取消注释第二段代码会发生什么?