0

My date picker, when initialized, looks like this: enter image description here

However, after changing it in the simulator, it looks like this: enter image description here

The weird thing is that sometimes this happens and sometimes it doesn't. When I select June 9th it keeps the long format and anything before 1975 does as well, as long as many other random dates.

How do I format the showcase text to always be the same?

Thanks!

Edit:

Here is a GIF of the selection process.

enter image description here

Code:

DatePicker(selection: $dob, in: ...Date(), displayedComponents: [.date]) {
                                    HStack(spacing: 0) {
                                        Text("Select birthday ")
                                        Image(systemName: "arrow.right")
                                    }
                                    .foregroundColor(Color("textfield"))
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
Hackinator
  • 132
  • 8
  • How can you change the date format exactly? don't you just pick the region? – hasan Jun 10 '21 at 08:58
  • I added a GIF to my original question to show what I'm talking about. I want to get the same long date format (MMM, d, yyyy) for every day I select. – Hackinator Jun 10 '21 at 09:07
  • @JoakimDanielson Sorry, I'm a little bit confused. In the GIF when I select some dates, it shows the long format, but others show the short format. How can I make it so all show the long format / all show the short format? I don't really mind using it the way it is but I was curious on how I could customize this. Or is something I'm doing selecting the format without my knowing? (relatively new to SwiftUI). Also, I have researched date formats and I'm not sure how to apply it to a date picker in SwiftUI iOS14, that's actually the first thing I researched. – Hackinator Jun 10 '21 at 09:15
  • I didn't see that before in the GIF, this looks more like an issue with the DatePicker, see https://stackoverflow.com/questions/66090210/swiftui-datepicker-jumps-between-short-and-medium-date-formats-when-changing-the – Joakim Danielson Jun 10 '21 at 09:21
  • Thank you! Just the type of discussion I was looking for but couldn't find :-) – Hackinator Jun 10 '21 at 09:27

1 Answers1

1

I had the same problem. I solved it by adding .id

Example:

DatePicker(selection: $dob, in: ...Date(), displayedComponents: [.date]) {
    HStack(spacing: 0) {
       Text("Select birthday ")
       Image(systemName: "arrow.right")
    }
    .foregroundColor(Color("textfield"))
}
.id(dob)

This prevents the date picker from being created more than once.

Source: SwiftUI DatePicker jumps between short and medium date formats when changing the date

Ever CR
  • 351
  • 3
  • 7