gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:48:15 24 4
gpt4 key购买 nike

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

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 View ,我希望日期选择器和切换器更改计时器数组中保存的值,但我不知道如何在 SwiftUI 中使用 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())
}
}
}
}
}
}

最佳答案

通过广泛查看 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())
}
}
}

关于datepicker - 如何在 SwiftUI 中将 ObservedObject 与 DatePicker 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59602342/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com