我正在使用一个类来存储 @Published 变量,但是当我尝试将自定义 DatePicker 上选择的值传递给类中的 @ObservedObject 时,我收到以下错误:
TimePicker(time: self.$time.**timeSelected**)
无法将“Binding”(又名“Binding”)类型的值转换为预期的参数类型“TimeModel”
如何使用选择器值更新 @ObservedObject?
完整代码:
struct ContentView: View {
@ObservedObject var time = TimeModel()
var body: some View {
ZStack{
VStack{
TimePicker(time: self.$time.timeSelected)
Text("You chose \(time.timeSelected/60) minutes")
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
class TimeModel: ObservableObject{
@Published var timeSelected: TimeInterval = 1.0
}
struct TimePicker: UIViewRepresentable {
@ObservedObject var time = TimeModel()
func makeUIView(context: Context) -> UIDatePicker {
let datePicker = UIDatePicker()
datePicker.datePickerMode = .countDownTimer
datePicker.addTarget(context.coordinator,
action: #selector(Coordinator.updateTime),
for: .valueChanged)
return datePicker
}
func updateUIView(_ datePicker: UIDatePicker, context: Context) {
datePicker.minuteInterval = 5
datePicker.countDownDuration = time.timeSelected
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject {
let parent: TimePicker
init(_ parent: TimePicker) {
self.parent = parent
}
@objc func updateTime(datePicker: UIDatePicker) {
parent.time.timeSelected = datePicker.countDownDuration
}
}
}