使用swiftUI如何仅在textField处于编辑模式时才添加datePicker?

时间:2019-06-07 06:36:56

标签: uitextfield uidatepicker swiftui vstack hstack

我现在在HStack内添加了datePicker。我只想在datePicker处于编辑模式时显示textField

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 个答案:

答案 0 :(得分:1)

您可以将onEditingChanged与绑定结合使用以获得所需的效果。

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