0

DatePicker on Button Click.

I already tried many code but none of them worked for me,

HStack {
   Image(systemName: "calendar")
        
    Button(action: {
       
    }, label: {
         Text("Today")
           .font(.system(size: 17, weight: .semibold, design: .rounded))          
    })
    
    Spacer()
    Image(systemName: "arrowtriangle.down.fill")
        .font(.system(size: 16, weight: .semibold))
}

that's my button code, I want to implement the date when user tapped on Today text. Really want your help

vadian
  • 274,689
  • 30
  • 353
  • 361

1 Answers1

0

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())
}
sats
  • 647
  • 6
  • 17