如何在SwiftUI中将ObservedObject与DatePicker一起使用?

时间:2020-01-05 17:21:20

标签: datepicker swiftui

此类接收和发送更新计时器数组的网络请求

struct ScheduleTimer: Identifiable {
    var id: Int
    var name: String
    @State var start: Date
    @State var end: Date
    @State var isActive: Bool
}

class ScheduleController: ObservableObject, NetworkDelegate {

    var didChange = PassthroughSubject<Void, Never>()

    @Published var timers = [ScheduleTimer]()
...

这是我的SwiftUI视图,在这里我希望日期选择器和切换器更改保存在timers数组中的值,但我不知道如何在TimerUI中使用timer.start,timer.end和timer.isActive引发错误。

struct ScheduleView: View {
    @ObservedObject var scheduleController = ScheduleController()

    var body: some View {
        NavigationView {
            Form {
                ForEach(scheduleController.timers) { timer in
                    Section(header: Text(timer.name)){
                        DatePicker("From", selection: timer.start, displayedComponents: .hourAndMinute)
                        DatePicker("To", selection: timer.end, displayedComponents: .hourAndMinute)
                        Toggle(isOn: timer.isActive) {
                            Text("")
                        }.toggleStyle(DefaultToggleStyle())
                    }
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

通过广泛查看Apple的SwiftUI教程来解决该问题:https://developer.apple.com/tutorials/swiftui/handling-user-input

struct ScheduleTimer: Identifiable {
    var id: Int
    var name: String
    var start: Date
    var end: Date
    var isActive: Bool
}

struct ScheduleView: View {
    @ObservedObject var scheduleController = ScheduleController()

    var body: some View {
        NavigationView {
            Form {
                ForEach(scheduleController.timers) { timer in
                    ScheduleForm(scheduleController: self.scheduleController, timer: timer)
                }
            }
        }
    }
}


struct ScheduleForm: View {
    @ObservedObject var scheduleController: ScheduleController
    var timer: ScheduleTimer
    var scheduleIndex: Int {
        scheduleController.timers.firstIndex(where: { $0.id == timer.id })!
    }
    @State var start = Date()
    var body: some View {
        Section(header: Text(self.scheduleController.timers[scheduleIndex].name)){
            DatePicker("From", selection: self.$scheduleController.timers[scheduleIndex].start, displayedComponents: .hourAndMinute)
            DatePicker("To", selection: self.$scheduleController.timers[scheduleIndex].end, displayedComponents: .hourAndMinute)
            Toggle(isOn: self.$scheduleController.timers[scheduleIndex].isActive) {
                Text("")
            }.toggleStyle(DefaultToggleStyle())
        }
    }
}