我正在基于视图模型制作滑块,但我面临此错误消息
Initializer 'init(value:in:step:label:minimumValueLabel:maximumValueLabel:onEditingChanged:)' requires that 'Int.Stride' (aka 'Int') conform to 'BinaryFloatingPoint'
这很奇怪,因为将整数从视图模型转换为 Double 并不能完全解决问题。
我发现了非常相似的问题并阅读了SO答案(如何使 Int 符合 BinaryFloatingPoint 或 Double/CGFloat 符合 BinaryInteger?),但似乎我无法为我的案例实现解决方案,可能是因为我使用
ObservedObject
作为视图模型。
如果我删除
$
前面的 setInformationVM.elapsedRestTime
,我会看到另一条错误消息:Cannot convert value of type 'Int' to expected argument type 'Binding<Int>'
他们说“当需要双向通信时通常会使用绑定”——这是否意味着滑块需要一种与视图模型通信/更新的方法? 为什么滑块接受
@State private var xx: Double
作为一般值,而不是我的视图模型中的简单整数?
import Foundation
import SwiftUI
import Combine
struct SetRestDetailView: View {
@EnvironmentObject var watchDayProgramVM: WatchDayProgramViewModel
@State var showingLog = false
var body: some View {
GeometryReader { geometry in
ZStack() {
(view content removed for readability)
}
.sheet(isPresented: $showingLog) {
let setInformatationVM = self.watchDayProgramVM.exerciseVMList[0].sets[2]
setLoggingView(setInformationVM: setInformatationVM, suitability: 3, stepValue: 10)
}
}
}
设置LoggingView
struct setLoggingView: View {
@Environment(\.dismiss) var dismiss
@ObservedObject var setInformationVM: SetInformationTestClass
@State var suitability: Int
var stepValue: Int
var body: some View {
GeometryReader { geometry in
let rect = geometry.frame(in: .global)
ScrollView {
VStack(spacing: 5) {
Text("Rested \(Int(setInformationVM.elapsedRestTime)) sec")
Slider(value: $setInformationVM.elapsedRestTime,
in: 0...setInformationVM.totalRestTime,
step: Int.Stride(stepValue),
label: {
Text("Slider")
}, minimumValueLabel: {
Text("-\(stepValue)")
}, maximumValueLabel: {
Text("+\(stepValue)")
})
.tint(Color.white)
.padding(.bottom)
Divider()
Spacer()
Text("suitability")
.frame(minWidth: 0, maxWidth: .infinity)
suitabilityStepper(rect: rect, maxsuitabilityness: 5, minsuitabilityness: 1, suitabilityIndex: restfullness)
Button(action: {
print("Update Button Pressed")
//TODO
//perform further actions to update suitability metric and elapsed rest time in the viewmodels before dismissing the view, and also update the iOS app by synching the view model.
dismiss()
}) {
HStack {
Text("Update")
.fontWeight(.medium)
}
}
.cornerRadius(40)
}
.border(Color.yellow)
}
}
}
SetInformationTestClass视图模型
class SetInformationTestClass: ObservableObject {
init(totalRestTime: Int, elapsedRestTime: Int, remainingRestTime: Int, isTimerRunning: Bool) {
self.totalRestTime = totalRestTime
self.elapsedRestTime = elapsedRestTime
self.remainingRestTime = remainingRestTime
}
@Published var totalRestTime: Int
@Published var elapsedRestTime: Int
@Published var remainingRestTime: Int
您可以创建自定义绑定变量,例如:
let elapsedTime = Binding(
get: { Double(self.setInformationVM.elapsedRestTime) },
set: { self.setInformationVM.elapsedRestTime = Int($0) } // Or other custom logic
)
// then you reference it in the slider like:
Slider(elapsedTime, ...)