运行 在 SwiftUI didSet 函数中更改 DatePicker 中的日期时的代码?
Run code when date in DatePicker is changed in SwiftUI didSet function?
struct ViewName: View {
@State private var selectedDay: Date = Date() {
didSet {
print("Old value was \(oldValue) and new date is \(self.selectedDay)")
}
}
var body: some View {
VStack {
DatePicker(selection: $selectedDay, in: Date()..., displayedComponents: .date) { Text("") }
}
}
}
我的问题是,当我在 DatePicker 中设置 selectedDate 值时,为什么没有任何内容打印到控制台?
My question is, when I'm setting the selectedDate value in the DatePicker, why is there nothing printed to the console?
目前 didSet
不适用于 @State
属性 包装器。
这是一种对 DatePicker 选择产生副作用的方法已更改
struct ViewName: View {
@State private var selectedDay = Date()
var body: some View {
let dateBinding = Binding(
get: { self.selectedDay },
set: {
print("Old value was \(self.selectedDay) and new date is \([=10=])")
self.selectedDay = [=10=]
}
)
return VStack {
DatePicker(selection: dateBinding, in: Date()..., displayedComponents: .date) { Text("") }
}
}
}
struct ViewName: View {
@State private var selectedDay: Date = Date() {
didSet {
print("Old value was \(oldValue) and new date is \(self.selectedDay)")
}
}
var body: some View {
VStack {
DatePicker(selection: $selectedDay, in: Date()..., displayedComponents: .date) { Text("") }
}
}
}
我的问题是,当我在 DatePicker 中设置 selectedDate 值时,为什么没有任何内容打印到控制台?
My question is, when I'm setting the selectedDate value in the DatePicker, why is there nothing printed to the console?
目前 didSet
不适用于 @State
属性 包装器。
这是一种对 DatePicker 选择产生副作用的方法已更改
struct ViewName: View {
@State private var selectedDay = Date()
var body: some View {
let dateBinding = Binding(
get: { self.selectedDay },
set: {
print("Old value was \(self.selectedDay) and new date is \([=10=])")
self.selectedDay = [=10=]
}
)
return VStack {
DatePicker(selection: dateBinding, in: Date()..., displayedComponents: .date) { Text("") }
}
}
}