how to use datePicker in textfield when click selected?

I want to use datepicker in textfield for select date of birth.

Answered by Claude31 in 398483022

You should have said you wanted to do in SwiftUI.


Have a look here (even though it has some errors but it shows the principles)


https://stackoverflow.com/questions/56489107/using-swiftui-how-can-i-add-datepicker-only-while-textfield-is-in-editing-mode


This works:


struct ContentView: View {
    var dateFormatter: DateFormatter {
        let formatter = DateFormatter()
        formatter.dateStyle = .long
        return formatter
    }

    @State private var birthDate = Date()

    var body: some View {
        VStack {
            Text("Select a date")
            DatePicker(selection: $birthDate, in: ...Date(), displayedComponents: .date) {
                Text("date")
            }
            Text("Birth date is \(birthDate, formatter: dateFormatter)")
        }.labelsHidden()
    }

}

What do you want ? Select the date in the picker and display it in textField ?


What you have to do

- create a textField (or a label) and a date picker that is intially hidden

- connect the textField to an IBOutlet

- when clicking in the textField, show the date picker over the textField

- When you have selected the date of birth in Picker, write the selection in textField

- Hide the date picker

I want to tab textfield and have a picker view select date and press done in swiftUi.

Accepted Answer

You should have said you wanted to do in SwiftUI.


Have a look here (even though it has some errors but it shows the principles)


https://stackoverflow.com/questions/56489107/using-swiftui-how-can-i-add-datepicker-only-while-textfield-is-in-editing-mode


This works:


struct ContentView: View {
    var dateFormatter: DateFormatter {
        let formatter = DateFormatter()
        formatter.dateStyle = .long
        return formatter
    }

    @State private var birthDate = Date()

    var body: some View {
        VStack {
            Text("Select a date")
            DatePicker(selection: $birthDate, in: ...Date(), displayedComponents: .date) {
                Text("date")
            }
            Text("Birth date is \(birthDate, formatter: dateFormatter)")
        }.labelsHidden()
    }

}

Have you finally solved your problem ?


If so, don't forget to close the thread.

how to use datePicker in textfield when click selected?
 
 
Q