Search code examples
swiftuidatepicker

SwiftUI DatePicker issue iOS 17.1


The code below is working fine in iOS 17.0.1, but in the latest update, 17.1 DatePicker does not open when we tap on it.

After several tries, I found that on the long press, around 2-3 seconds, it opens the date picker.

Any solution for this issue? How do I open only on tap?

VStack(alignment: .leading){
Text("Date".localized())
    .applyFont(style: .Medium, size: 18)
    .foregroundColor(Colors.grayLight)
        HStack{
            let lastYear = Calendar.current.date(byAdding: .year, value: -1, to: Date()) ?? Date()
                if let date = checkLowerBound(){
                    DatePicker("",selection:$selectedDate, in: date...Date(), displayedComponents: [.date])
                        .frame(width: 100)
                    }else{
                    DatePicker("",selection:$selectedDate, in: lowestDate...Date(), displayedComponents: [.date])
                        .frame(width: 100)
                    }
                    Spacer()
                    }
                    .padding(.horizontal, 10)
                }
    .cardProperty()
    .allowsHitTesting(!(eventTransaction != nil && eventTransaction?.by != UserDefaults.userID))

Solution

  • It appears that if a TapGesture is handles somewhere higher in the hierarchy, as of 17.1, the DatePicker with displayedComponents: .date will defer to it, and not trigger its own behavior.

    simultaneousGesture does not appear to help. However, I found a hacky solution. By wrapping the DatePicker with its own TapGesture handler with a required Count, this buggy behavior will not be triggered as long as the count is not fulfilled.

    Minimal viable triggering code with solution:

    struct ContentView: View {
    @State private var date = Date()
    
    var body: some View {
        VStack {
            DatePicker(
                "Foo",
                selection: $date,
                displayedComponents: .date
            )
            .onTapGesture(count: 99, perform: {
                // overrides tap gesture to fix ios 17.1 bug
            })
        }
        .onTapGesture {
        }
      }
    }