How to disable past date in ckcalendar?

2k Views Asked by At

I am looking for how to disable past dates in the CKCalendar. For instance, I want to disable all dates before the current date. Only today's date and the future date must be clickable.

3

There are 3 best solutions below

2
On BEST ANSWER

In addition to Larme's comment (setting calendar:willSelectDate to return NO for past dates), if you want to configure the colors for those "disabled dates", you can do so by setting up the delegate method configureDateItem: forDate:.

An example:

- (void)calendar:(CKCalendarView *)calendar configureDateItem:(CKDateItem *)dateItem forDate:(NSDate *)date {

    if([date laterDate:minimumDate] == minimumDate) {
        dateItem.textColor = [UIColor grayColor];
    }
}

The above code sets the text color of all past dates to gray.

An example for willSelectDate delegate method:

- (BOOL)calendar:(CKCalendarView *)calendar willSelectDate:(NSDate *)date {
    if ([date laterDate:minimumDate] == minimumDate) {
        return NO;
    }
    return [calendar dateIsInCurrentMonth:date];
}

The above code disables selection of all past dates.

0
On

Just give this condition

calendar.onlyShowCurrentMonth=YES;
0
On

If you are looking SwiftUI solution..

First you need to make partial range from in case you want to make previous dates unelectable

let dateRange: PartialRangeFrom<Date> = {
        let calendar = Calendar.current
        let startComponents = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: Date.now)
        return calendar.date(from: startComponents)!...
    }()

then you can configure Date picker passing the range, you just created

DatePicker("", selection: $dueDate, in: dateRange)
           .datePickerStyle(.graphical)
           .labelsHidden()