你好,我有两个日期选择器,一个只用于日期,另一个用于小时和分钟
if(showStartDatePicker) {
DatePicker("Seleziona data", selection: $selectedStartDate,/* in: startingDate...endingDate,*/ displayedComponents: [.date])
.datePickerStyle(.graphical)
} else if(showStartTimePicker) {
DatePicker("Select a date", selection: $selectedStartTime, displayedComponents: [.hourAndMinute])
.datePickerStyle(.wheel)
}
我需要获得一个单一的日期,这是两个日期选择器的合并
那我该怎么办呢?
只需共享变量,而不需要2个
struct DoubleDatePickerView: View {
@State var showStartDatePicker: Bool = false
@State var selectedStartDate: Date = Date()
var body: some View {
VStack{
Text(selectedStartDate.description)
if(showStartDatePicker) {
DatePicker("Seleziona data", selection: $selectedStartDate,/* in: startingDate...endingDate,*/ displayedComponents: [.date])
.datePickerStyle(.graphical)
Button("show time picker", action: {
showStartDatePicker.toggle()
})
} else {
DatePicker("Select a date", selection: $selectedStartDate, displayedComponents: [.hourAndMinute])
.datePickerStyle(.wheel)
Button("show date picker", action: {
showStartDatePicker.toggle()
})
}
}
}
}
另一种选择是从每个可变中组合所需的组件
var combined: Date{
let timeComponents: DateComponents = Calendar.current.dateComponents([.hour,.minute,.second,.timeZone], from: selectedStartTime)
let dateComponents: DateComponents = Calendar.current.dateComponents([.year,.month,.day], from: selectedStartDate)
let combined: DateComponents = .init(calendar: .current, timeZone: timeComponents.timeZone, year: dateComponents.year, month: dateComponents.month, day: dateComponents.day, hour: timeComponents.hour, minute: timeComponents.minute, second: timeComponents.second)
return Calendar.current.date(from: combined) ?? Date()
}