首页 > 解决方案 > 在 DatePicker 中调用 .onChange 之前的函数

问题描述

我已经做到了,所以每当我更改 DatePicker 中的日期时,Xcode 都会像这样打印所选日期:

DatePicker("Date", selection: $date, in: range, displayedComponents: .date)
        .datePickerStyle(GraphicalDatePickerStyle())
        .onChange(of: date) {
            print(date)
            print($0)
        }

但是,当视图首次出现时,我想打印默认选择的日期(今天的日期)。在 DatePicker 中更改日期之前,如何打印默认日期?

另外,因为我在它。为什么每当我删除 print($0) 时,都会出现以下错误:

Cannot convert value of type 'Date' to expected argument type '()'

标签: swiftuidatepicker

解决方案


替代 1:

.onAppear{ print(date) }

备选案文 2:

  .onChange(of: date) { [date] newDate in
                        print("From \(date) to \(newDate)" )
                    }

=> 这样,您想要的两个值都将显示。希望这也能回答你的问题2。


推荐阅读