如何在UIDatePicker中禁用特定日期



>我有一个UIDatePicker,应该只显示特定的日子,就像所有星期日和星期一一样,并禁用所有其他日期,用户只能选择从本周、下周、后周到2020年的星期日和星期一。

这甚至可以使用UIDatePicker甚至任何自定义控件吗?

我建议你这样使用:

从下面的代码中,您将获得2016-2018年所有星期日的日期,

let cal = Calendar.current
// Get the date of 2 years ago today
let stopDate = cal.date(byAdding: .year, value: -2, to: Date())!
// We want to find dates that match on Sundays at midnight local time
var comps = DateComponents()
comps.weekday = 1 // Sunday
// Enumerate all of the dates
cal.enumerateDates(startingAfter: Date(), matching: comps, matchingPolicy: .previousTimePreservingSmallerComponents, repeatedTimePolicy: .first, direction: .backward) { (date, match, stop) in
if let date = date {
if date < stopDate {
stop = true // We've reached the end, exit the loop
} else {
print("(date)") // do what you need with the date
}
}
}

逻辑很简单。在您需要的dateFormat中制作一个数组,并在pickerView中显示它,最终将为您datePicker

希望这有帮助。

这是不可能的。您必须基于 UIPickerView 创建自定义日期选择器。

一种方法可以只UIDatePicker来做到这一点!

假设您有一个January 16 10:00AMminTime

你会做这样的事情:

let picker = UIDatePicker()
picker.minimumDate = minTime
picker.maximumDate = minTime.changing(.hour, value: 23).changing(.minute, value: 59)

然后,选取器将卡在该日期。 希望这对某人有所帮助!

最新更新