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)
}
1
  • There is onEditingChanged in TextField.init. Commented Jun 7, 2019 at 6:56

1 Answer 1

2

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)
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

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).
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.