如何在UIDatePicker中禁用特定日期

时间:2018-05-02 12:54:01

标签: ios calendar uidatepicker

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

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

3 个答案:

答案 0 :(得分:1)

我建议你这样使用:

从下面的代码中,您将获得 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使用。

希望这有帮助。

答案 1 :(得分:0)

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

答案 2 :(得分:0)

有一种方法可以做到,只需UIDatePicker即可

假设您有一个minTime的{​​{1}}

您将执行以下操作:

January 16 10:00AM

然后,选择器将停留在该日期。 希望这对某人有帮助!