从日期选择器中隐藏过去的日期和时间 swift

Hide past date and time from date picker swift

我正在尝试隐藏日期选择器过去的日期。但我无法隐藏。有什么办法可以隐藏过去的日期和时间。当我设置为最小日期时,我能够禁用过去的日期。那么有什么方法可以从日期选择器中隐藏过去的日期吗?

解决方案:

将日期选择器的最小日期设置为当前日期。

datePicker.minimumDate = Date()

您可以按照以下 SO 问题作为参考:

iOS: UIDatePicker "remove" dates outside min and max dates

注意:最小日期 属性 将禁用过去日期的选择,但它不会隐藏日期,而是将其灰显。

var dateCollection = [Date]()

func selectedDate()->Int{
    dateCollection = buildDateCollection()
    var row = 0
    for index in dateCollection.indices{
    let today = Date()
    if Calendar.current.compare(today, to: dateCollection[index], toGranularity: .day) == .orderedSame{
row = index
        }
    }
    return row
}

func buildDateCollection()-> [Date]{
   dateCollection.append(contentsOf: Date.nextYear())
   return dateCollection
}

func formatDatePicker(date: Date) -> String{
    formatter.dateFormat = DATE_PICKER_FORMAT_CUSTOM
    return formatter.string(from: date)
}

func formatDate(date: Date) -> String{
    formatter.dateFormat = SECURIY_CONC_CLIENT_FORMAT_PNDING
    return formatter.string(from: date)
}

override func viewDidLoad() {
    super.viewDidLoad()        
    let _ = selectedDate()
}

func setPickerView() {
    picker.tag = tag
    picker.delegate = self
    txtField_Date.dataSource = self
    txtField_Date.inputView = picker
}

func numberOfComponents(in pickerView: UIPickerView) -> Int {
     return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return dateCollection.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return formatDatePicker(date: dateCollection[row])
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
     txtField_Date.text = formatDate(date: self.dateCollection[row])
}

输出屏幕截图: