SwiftUI: unfocus TextField when DatePicker date has been chosen

I have a DatePicker and TextField which should be synced.

When I choose date in DatePicker value is updated in TextField.

When I type date in TextField value is updated in DatePicker, but I choose date in DatePicker after that TextField stay focused and value didn’t update.

I read about @FocusState but iOS 14 should be supported.

How can I say TextField get lost focus when I tapped on DatePicker?

import SwiftUI
import Combine

struct ContentView: View {
    @State private var selectedDate = Date()
    @State private var isHidden = true


    let formatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "MM/dd/yyyy"
        return formatter
    }()

    var body: some SwiftUI.View {
        VStack(alignment: .center) {
            ZStack {

                HStack(alignment: .center) {

                    Text("Start Date")
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .background(Color.yellow)
                        .onTapGesture {
                        self.onExpandTapped()
                    }
                    Spacer()
                        .background(Color.yellow)
                    if isHidden {
                        Text(selectedDate, style: .date)
                            .onTapGesture {
                            self.onExpandTapped()
                        }
                    } else {
                        TextField("Date", value: $selectedDate, formatter: formatter)
                            .multilineTextAlignment(.trailing)
                            .background(Color.red)
                            .fixedSize()

                    }
                }
            }

            if !isHidden {
                DatePicker("",
                    selection: $selectedDate,
                    displayedComponents: .date)
                    .padding(.horizontal)
                    .frame(width: 333)
                    .datePickerStyle(.graphical)
                    .labelsHidden()

            }
        }
    }

    private func onExpandTapped() {
        isHidden.toggle()
        UIApplication.shared.endEditing()
    }
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}


extension UIApplication {
    func endEditing() {
        sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
    }
}

enter image description here

>Solution :

Try computable binding with side effect.. this should be activated only from within DataPicker:

DatePicker("",
    selection: Binding(get: {selectedDate}, set:{
       selectedDate = $0
       UIApplication.shared.endEditing()    // << here !!
    }),
    displayedComponents: .date)
    .padding(.horizontal)
    .frame(width: 333)
    .datePickerStyle(.graphical)
    .labelsHidden()

Leave a Reply