SwiftUI DatePicker绑定可选日期,有效为nil [英] SwiftUI DatePicker Binding optional Date, valid nil

查看:232
本文介绍了SwiftUI DatePicker绑定可选日期,有效为nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试 https:// alanquatermain.me/programming/swiftui/2019-11-15-CoreData-and-bindings/

我的目标是让DatePicker绑定到Binding <日期? >允许使用零值,而不是初始化为Date();如果您在核心数据模型实体中具有Date属性并且接受nil作为有效值,则此方法很有用。

my goal is to have DatePicker bind to Binding< Date? > which allow for nil value instead of initiate to Date(); this is useful, if you have Date attribute in your core data model entity which accept nil as valid value.

这是我的快捷代码:

extension Binding {
    init<T>(isNotNil source: Binding<T?>, defaultValue: T) where Value == Bool {
        self.init(get: { source.wrappedValue != nil },
                  set: { source.wrappedValue = $0 ? defaultValue : nil})
    }
}

struct LiveView: View {
    @State private var testDate: Date? = nil
    var body: some View {
        VStack {
            Text("abc")

            Toggle("Has Due Date",
                   isOn: Binding(isNotNil: $testDate, defaultValue: Date()))

            if testDate != nil {
                DatePicker(
                    "Due Date",
                    selection: Binding($testDate)!,
                    displayedComponents: .date
                )
            }
        }
    }
}

let liveView = LiveView()
PlaygroundPage.current.liveView = UIHostingController(rootView: liveView)

我可以找不到解决此代码的解决方案。第一次打开切换开关时,它可以工作,但关闭切换开关时,它会崩溃。

I can't find solution to fix this code. It works when the toggle first toggled to on, but crash when the toggle turned back off.

当我删除DatePicker并更改代码时,代码似乎工作正常遵循以下条件:

The code seems to behave properly when I removed the DatePicker, and change the code to following:

extension Binding {
    init<T>(isNotNil source: Binding<T?>, defaultValue: T) where Value == Bool {
        self.init(get: { source.wrappedValue != nil },
                  set: { source.wrappedValue = $0 ? defaultValue : nil})
    }
}

struct LiveView: View {
    @State private var testDate: Date? = nil
    var body: some View {
        VStack {
            Text("abc")

            Toggle("Has Due Date",
                   isOn: Binding(isNotNil: $testDate, defaultValue: Date()))

            if testDate != nil {
                Text("\(testDate!)")
            }
        }
    }
}

let liveView = LiveView()
PlaygroundPage.current.liveView = UIHostingController(rootView: liveView)

我怀疑这与这段代码有关

I suspect it's something to do with this part of the code

DatePicker("Due Date", selection: Binding($testDate)!, displayedComponents: .date )

问题,当source.wrappedValue设置回nil时(请参阅绑定扩展)

problem when the source.wrappedValue set back to nil (refer to Binding extension)

推荐答案

问题是 DatePicker 会抢占绑定,即使将其从视图中删除也无法很快地释放它,由于 Togg le 动作,因此在强制展开可选动作时崩溃,该动作变为零...

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

此崩溃的解决方法是

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

这篇关于SwiftUI DatePicker绑定可选日期,有效为nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆