Swiftui Datepicker Binding Optional Date, Valid Nil

SwiftUI DatePicker Binding optional Date, valid nil

The problem is that DatePicker grabs binding and is not so fast to release it even when you remove it from view, due to Toggle action, so it crashes on force unwrap optional, which becomes nil ...

The solution for this crash is

DatePicker(
"Due Date",
selection: Binding<Date>(get: {self.testDate ?? Date()}, set: {self.testDate = $0}),
displayedComponents: .date
)

Is it possible to set SwiftUI DatePicker minimumDate using bindings?

Here is the solution. Minimum and maximum dates were deprecated in SwiftUI DatePickers. The changes and solution were posted here: https://sarunw.com/posts/swiftui-changes-in-xcode-11-beta-4

If the link does not work, here are the examples.

DatePicker deprecated initializers
Initializers with minimumDate and maximumDate are gone. Now we initialized it with ClosedRange, PartialRangeThrough, and PartialRangeFrom.

We use PartialRangeFrom for minimumDate.

DatePicker("Minimum Date",
selection: $selectedDate,
in: Date()...,
displayedComponents: [.date])

We use PartialRangeThrough for maximumDate.

DatePicker("Maximum Date",
selection: $selectedDate,
in: ...Date(),
displayedComponents: [.date])

If you want to enforce both minimumDate and maximumDate use ClosedRange

@State var selectedDate = Date()

var dateClosedRange: ClosedRange<Date> {
let min = Calendar.current.date(byAdding: .day, value: -1, to: Date())!
let max = Calendar.current.date(byAdding: .day, value: 1, to: Date())!
return min...max
}

DatePicker(
selection: $selectedDate,
in: dateClosedRange,
displayedComponents: [.hourAndMinute, .date],
label: { Text("Due Date") }
)

In all of the examples, the Date() can be replaced with a binding that is of type Date.

Bind @State to optional @Binding in the same struct SwiftUI

Add a custom init. With that, newAssignment var is also not needed.

struct AssignmentEditMenu: View {

@EnvironmentObject var planner: Planner
@Environment(\.dismiss) var dismiss

var isEditing // set to true if assignment is not nil

var assignment: Binding<Assignment>

init(a: Binding<Assignment> = .constant(Assignment())) {
assignment = a
}

.....

}


Related Topics



Leave a reply



Submit