Use the DatePicker
provided by SwiftUI.
Declare state variables - one to store the date and another to conditionally show or hide the DatePicker
.
@State var date = Date()
@State var isDatePickerVisible = false
Set isDatePickerVisible
to true
when the user clicks on the button.
Button(action: {
isDatePickerVisible = true
}, label: {
Text("Today")
.font(.system(size: 17, weight: .semibold, design: .rounded))
})
Show the DatePicker when the isDatePickerVisible
flag is set to true
.
Clicking on the done button will hide the DatePicker
again.
if isDatePickerVisible {
HStack {
DatePicker("", selection: $date)
.datePickerStyle(GraphicalDatePickerStyle())
.frame(maxHeight: 400)
Button("Done", action: {
isDatePickerVisible = false
})
}
}
You can also display the selected date in a Text
using the following code.
Text("Date is \(date.formatted(date: .long, time: .omitted))")
However, if you want to display the current date when the user clicks on Today instead of letting the user pick a date, use the following code:
if isDatePickerVisible {
Text(Date.now, format: .dateTime.day().month().year())
}