您好,我有兩個日期選擇器,一個僅用于日期,另一個用于小時和分鐘
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)
}
我需要獲得一個日期,它是兩個日期選擇器的合并
那我該怎么辦?
uj5u.com熱心網友回復:
只需共享變數而不是 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()
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/430541.html
下一篇:SwiftUI中的回圈問題
