gpt4 book ai didi

ios - SwiftUI DatePicker Binding optional Date, valid nil

转载 作者:行者123 更新时间:2023-11-29 13:51:55 25 4
gpt4 key购买 nike

我正在试验来自 https://alanquatermain.me/programming/swiftui/2019-11-15-CoreData-and-bindings/ 的代码

我的目标是让 DatePicker 绑定(bind)到 Binding 允许 nil 值而不是初始化 Date();这很有用,如果你的核心数据模型实体中有 Date 属性,它接受 nil 作为有效值。

这是我的 swift playground 代码:

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)

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

当我删除 DatePicker 并将代码更改为以下代码时,代码似乎表现正常:

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)

我怀疑这与这部分代码有关

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

当 source.wrappedValue 设置回 nil 时的问题(引用 Binding 扩展)

最佳答案

问题是 DatePicker 会获取绑定(bind),即使您将其从 View 中移除,也不会很快释放它,由于 Toggle 操作,因此它会强制崩溃unwrap optional,变成 nil ...

这个崩溃的解决方案是

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

关于ios - SwiftUI DatePicker Binding optional Date, valid nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59272801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com