3

I have added datePicker for now inside HStack. I want to show datePicker only when textField is in editing mode.

struct EditProfile: View {
    @Binding var profile: Profile
    var body: some View {
        List {
            HStack {
                Text("Username").bold()
                TextField("Date")
                DatePicker(
                    $profile.goalDate,
                    minimumDate: Calendar.current.date(byAdding: .year, value: -1, to: profile.goalDate),
                    maximumDate: Calendar.current.date(byAdding: .year, value: 1, to: profile.goalDate),
                    displayedComponents: .date
                )
            }
        }
        .padding(.top)
    }
    .padding(.top)
}
PinkeshGjr
  • 8,460
  • 5
  • 41
  • 56

1 Answers1

1

You can use onEditingChanged along with binding to get the desired effect.

struct EditProfile : View {
    @Binding var profile: Profile
    @State var showDatePicker = false
    @State var textfieldText: String = ""

    var body: some View {
       List {
            HStack {
                Text("Username").bold()
                TextField($textfieldText, placeholder: Text("Date"), onEditingChanged: { (editting) in
                    self.showDatePicker = editting
                }) {

                }

                if self.showDatePicker {
                    DatePicker(
                        $profile.goalDate,
                        minimumDate: Calendar.current.date(byAdding: .year, value: -1, to: profile.goalDate),
                        maximumDate: Calendar.current.date(byAdding: .year, value: 1, to: profile.goalDate),
                        displayedComponents: .date
                    )
                }
            }
        }
        .padding(.top)
    }
}
Jake
  • 13,097
  • 9
  • 44
  • 73
  • Is this still working in Beta 7? Getting a weird error when I try to use this (it wants to take self.showDatePicker = editing and change it to self.showDatePicker == editing, which is nowheres near correct). – ShadowDES Aug 31 '19 at 04:23
  • This has an issue where the keyboard appears when the textfield is tapped and resigning first responder makes the textfield not update when selecting a date – Javier Heisecke Jul 27 '22 at 15:47