SwiftUI:有什么解决方案可以清除DatePicker中的值?

时间:2019-12-04 05:03:44

标签: swift swiftui

我正在寻找一种在SwiftUI中清除DatePicker值的解决方案。我尝试过,但没有成功。请检查:

struct EditProfileView: View {

    @State var birthDate = Date()

    var body: some View {
        Form {
            Section (header: Text("Birth day")) {
                DatePicker(selection: $birthDate, in: ...Date(), displayedComponents: .date) {
                    Text("Select a date")
                }
                HStack {
                    Text("You were born in \(birthDate, formatter: dateFormatter)")
                    .font(.subheadline)
                    .foregroundColor(Color.gray)
                    Spacer()
                    Button(action: {
                        self.clearDate()
                    }) {
                        Text("Clear")
                    }
                }
            }
        }
    }

    func clearDate () {
        self.$birthDate = nil
    }

}

这行代码不起作用:

self.$birthDate = nil

我认为由于Date类型无法离开nil,但我找不到解决该问题的方法

2 个答案:

答案 0 :(得分:0)

birthDate(而不是$birthDate)设置为以下值,默认设置为当前日期:

self.birthDate = Date()

答案 1 :(得分:-1)

您可以从日期创建绑定吗?

  struct EditProfileView: View {

            @State var birthDate : Date?

            var dateFormatter: DateFormatter {
                           let formatter = DateFormatter()
                           formatter.dateStyle = .short
                           return formatter
                         }

            var body: some View {
                Form {
                    Section (header: Text("Birth day")) {
                        DatePicker(selection: Binding<Date>(get: { () -> Date in
                            self.birthDate ?? Date()
                        }, set: { (Date) in
                            self.birthDate = Date
                        }), in: ...Date(), displayedComponents: .date) {
                            Text("Select a date")
                        }
                        HStack {
                            Text( "You were born in :") + (birthDate == nil ? Text("") :  Text("\(birthDate!, formatter: dateFormatter)"))
                            .font(.subheadline)
                            .foregroundColor(Color.gray)
                            Spacer()
                            Button(action: {
                                self.clearDate()
                            }) {
                                Text("Clear")
                            }
                        }
                    }
                }
            }

            func clearDate () {
                self.birthDate = nil
            }

          }