UIDatePicker,显示YEAR和时间的完整日期

时间:2017-09-28 23:59:20

标签: ios swift uidatepicker swift4

您可以在DatePicker上显示UIDatePicker天,月,年和时间,还是需要自定义UIPickerView?即。

2000年11月12日星期一5月20日

目前,.datePickerMode设置为.dateTime的日期选择器显示

11月12日星期一上午5点20分

1 个答案:

答案 0 :(得分:1)

是的,你可以。但是你需要将两者结合起来。使用年份的选择器视图,并将您的日期选择器最小值设置为所选年份的第一天以及该年度的最大值。您还需要将UIDatePicker属性[datePickerMode] [1]设置为.dateAndTime

import UIKit

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
    @IBOutlet weak var pickerView: UIPickerView!
    @IBOutlet weak var datePicker: UIDatePicker!
    let years = Array(Date().year-3...Date().year+3)
    var date = Date()
    var lastIndex = 3
    override func viewDidLoad() {
        super.viewDidLoad()
        pickerView.delegate = self
        pickerView.dataSource = self
        datePicker.date = Date()
    }
    @IBAction func dateChanged(_ datePicker: UIDatePicker) {
        date = datePicker.date
        print(datePicker.date.year)
        print(datePicker.date)
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        pickerView.selectRow(3, inComponent: 0, animated: true)
        setDatePickerMinimumAndMaximumDatesFor(year: years[3])
    }
    func pickerView(_ pickerView: UIPickerView,
                    numberOfRowsInComponent component: Int) -> Int {
        return years.count
    }
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return String(years[row])
    }
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    func setDatePickerMinimumAndMaximumDatesFor(year: Int) {
        datePicker.minimumDate = year.firstDayOfTheYear
        datePicker.maximumDate = year.lastDayOfTheYear
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
setDatePickerMinimumAndMaximumDatesFor(year: years[row])
        if let optionalDate = Calendar.current.date(byAdding: .year, value: (lastIndex > row ? row - lastIndex :  -(lastIndex - row)), to: date) {
            datePicker.date = optionalDate
        }
        print(datePicker.date.year)
        print(datePicker.date)
    }
}
extension Date {
    var year: Int {
        return Calendar.current.component(.year, from: self)
    }
}
extension Int {
    var firstDayOfTheYear: Date {
        return DateComponents(calendar: .current, year: self, month: 1, day: 1).date!
    }
    var lastDayOfTheYear: Date {
        return DateComponents(calendar: .current, year: self, month: 12, day: 31).date!
    }
}