0

I am trying to use a DatePicker in swiftUI, but can't seem to find a way to give it specific times such as 8:00, 11:00, and 2:00. Is there a way to do it, and if so, how?

Currently I'm using this to do Time Intervals, but I don't think this helps with the current problem.

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
user17864647
  • 322
  • 2
  • 14
  • Create your DatePicker using an init that takes displayedComponents, like [this one](https://developer.apple.com/documentation/swiftui/datepicker/init(_:selection:in:displayedcomponents:)-7b6qq) and pass .timeAndHour as the value – Joakim Danielson Feb 21 '22 at 16:20
  • I don't follow, but if I understand this correctly, I've already set the type to .timeAndHour I need to only display specific times. – user17864647 Feb 21 '22 at 16:24
  • Not sure what you mean, if you already have some code then please share it. – Joakim Danielson Feb 21 '22 at 18:19

1 Answers1

0

You can't specify selected times in DatePicker.
But you could do something like this instead and and combine the values on commit:

struct ContentView: View {
    
    @State private var date = Date()
    @State private var time = "8:00"
    
    var body: some View {
        HStack {
            DatePicker("Select", selection: $date, displayedComponents: .date)
                .datePickerStyle(.compact)
                .background(.background)
            
            Picker("Time", selection: $time) {
                Text("2:00").tag("2:00")
                Text("8:00").tag("8:00")
                Text("11:00").tag("11:00")
            }
            .pickerStyle(.wheel)
            .frame(width: 100)
            .zIndex(-1)
        }
        .padding()
    }
}
ChrisR
  • 9,523
  • 1
  • 8
  • 26
  • This is the best answer, although, could you explain what the `.zIndex(-1)` does? Never seen or heard of it. – user17864647 Feb 22 '22 at 02:41
  • 1
    there is this annoying problem with two pickers next to each other, their active areas overlap and interfere. (search for picker here on SO and you'll find a lot of that). `.zIndex()`on a view defines the layering in z-direction, 0 is default. So by adding`.zIndex(-1)`to the 2nd picker puts it "behind" the first one. It's an easy fix, there are more sophisticated approaches out there. You will not need it if the pickers are further away from each other. – ChrisR Feb 22 '22 at 07:23