UIDatePicker返回当前日期而非选定日期

时间:2018-06-05 21:57:39

标签: ios swift uidatepicker

我有UIDatePicker,我根据下面的代码打印所选日期。但是,它不会打印所选日期,只打印当前日期。

@objc func setupDiscoverButton() {

    let cell = Bundle.main.loadNibNamed("FirstTableViewCell", owner: self, options: nil)?.first as! FirstTableViewCell

    // Date
    let sessionDate = cell.datePicker.date

    print("date: \(sessionDate)")
}

这是我为UIDatePicker定义的地方。

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = Bundle.main.loadNibNamed("FirstTableViewCell", owner: self, options: nil)?.first as! FirstTableViewCell

    // Date & time picker
    cell.datePicker.minimumDate = Date()
    cell.datePicker.timeZone = TimeZone.current

    // Discover button
    cell.discoverButton.addTarget(self, action: #selector(setupDiscoverButton), for: .touchUpInside)

    return cell
}

1 个答案:

答案 0 :(得分:0)

更改DatePicker听取datePickerChanged

datePicker.addTarget(self, action: #selector(datePickerChanged(picker:)), for: .valueChanged)

所以你的手机将是

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = Bundle.main.loadNibNamed("FirstTableViewCell", owner: self, options: nil)?.first as! FirstTableViewCell

    // Date & time picker
    cell.datePicker.minimumDate = Date()
    cell.datePicker.timeZone = TimeZone.current
cell.datePicker.addTarget(self, action: #selector(datePickerChanged(picker:)), for: .valueChanged)

    // Discover button
    cell.discoverButton.addTarget(self, action: #selector(setupDiscoverButton), for: .touchUpInside)

    return cell
}

  @objc func datePickerChanged(picker: UIDatePicker) {
        print(picker.date)
    }