我正在尝试构建一个可以处理可选日期的 DatePicker。
我把这篇文章作为一个起点......但我的代码,目前,在nil
和之间切换几次后就崩溃了Date()
。
我怎样才能使这段代码安全?
import SwiftUI
extension Date {
public var m3d2y4: String {
let formatter = DateFormatter()
formatter.dateFormat = "MMM dd, yyyy"
return formatter.string(from: self)
}
}
struct OptionalDatePicker: View {
@Binding var date: Date?
var nilText = "Never"
var nilDate = Date()
var body: some View {
if let _ = date {
datePicker
} else {
nilTextButton
}
}
private var dateBinding: Binding<Date> {
Binding(get: { date ?? nilDate }, set: { date = $0 })
}
private var dateString: String {
dateBinding.wrappedValue.m3d2y4
}
private var nilTextButton: some View {
Button(action: toggleDate) {
Text(nilText)
}
}
private var datePicker: some View {
ZStack {
HStack {
Text(dateString)
.foregroundColor(.blue)
Button(action: { toggleDate() }) {
Image(systemName: "xmark.circle")
}
}
DatePicker("", selection: dateBinding, displayedComponents: [.date])
.opacity(0.02) // minimum opacity to still allow tapping
.labelsHidden()
}
}
private func toggleDate() {
if let _ = date {
date = nil
} else {
date = nilDate
}
}
}
struct OptionalDatePicker_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
struct ContentView: View {
@State var date: Date? = nil
var body: some View {
HStack {
Text("Ends")
Spacer()
OptionalDatePicker(date: $date)
}
.padding()
}
}
}
提前致谢!