gpt4 book ai didi

swift - DatePicker 在 SwiftUI 中使用时间间隔

转载 作者:行者123 更新时间:2023-12-04 11:50:38 25 4
gpt4 key购买 nike

我想在 SwiftUI 中使用 DatePicker,它按预期工作正常。我想添加一个时间间隔,如解释:UIDatePicker 15 Minute Increments Swift

DatePicker("Please enter a time", selection: $wakeUp, displayedComponents: .hourAndMinute)

在 SwifUI 中是否有修改器?

最佳答案

我不相信有一个修饰符。但是,可以通过使用 UIViewRepresentable 包装 UIDatePicker 来“自己做”:



此代码的基本结构基于 Interfacing with UIKit教程。

struct MyDatePicker: UIViewRepresentable {

@Binding var selection: Date
let minuteInterval: Int
let displayedComponents: DatePickerComponents

func makeCoordinator() -> Coordinator {
return Coordinator(self)
}

func makeUIView(context: UIViewRepresentableContext<MyDatePicker>) -> UIDatePicker {
let picker = UIDatePicker()
// listen to changes coming from the date picker, and use them to update the state variable
picker.addTarget(context.coordinator, action: #selector(Coordinator.dateChanged), for: .valueChanged)
return picker
}

func updateUIView(_ picker: UIDatePicker, context: UIViewRepresentableContext<MyDatePicker>) {
picker.minuteInterval = minuteInterval
picker.date = selection

switch displayedComponents {
case .hourAndMinute:
picker.datePickerMode = .time
case .date:
picker.datePickerMode = .date
case [.hourAndMinute, .date]:
picker.datePickerMode = .dateAndTime
default:
break
}
}

class Coordinator {
let datePicker: MyDatePicker
init(_ datePicker: MyDatePicker) {
self.datePicker = datePicker
}

@objc func dateChanged(_ sender: UIDatePicker) {
datePicker.selection = sender.date
}
}
}

struct DatePickerDemo: View {
@State var wakeUp: Date = Date()
@State var minterval: Int = 1

var body: some View {
VStack {
Stepper(value: $minterval) {
Text("Minute interval: \(minterval)")
}
MyDatePicker(selection: $wakeUp, minuteInterval: minterval, displayedComponents: .hourAndMinute)
Text("\(wakeUp)")
}
}
}

struct DatePickerDemo_Previews: PreviewProvider {
static var previews: some View {
DatePickerDemo()
}
}

关于swift - DatePicker 在 SwiftUI 中使用时间间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60376694/

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