Search code examples
objective-ccocoapodsfscalendar

Disable selection to a range of dates in FSCalendar ObjC


I'm new to ObjC and I'm using FSCalendar library. I need to disable selection to a range of dates. Eg: from date - 2018-01-01 and to date - 2018-12-30. I've used the following method to disable past dates.

- (BOOL)calendar:(FSCalendar *)calendar shouldSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition

Please help me to disable selection of a range of dates


Solution

  • I'm not really familiar with FSCalendar, but I took a quick look and you should just be able to setup a startingDateToAvoid and endingDateToAvoid and then check if the date passed in from shouldSelectDate is within that range then return NO if it is (to disallow selection):

    #import "ViewController.h"
    #import "FSCalendar.h"
    
    @interface ViewController () <FSCalendarDelegate, FSCalendarDataSource>
    @property (strong, nullable) NSDate *startingDateToAvoid;
    @property (strong, nullable) NSDate *endingDateToAvoid;
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyy-MM-dd";
        self.startingDateToAvoid = [formatter dateFromString:@"2018-01-01"];
        self.endingDateToAvoid = [formatter dateFromString:@"2018-12-30"];
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    - (BOOL)_shouldAllowSelectionOfDate:(NSDate *)date {
        // if you want it to be inclusive of the starting/ending dates (i.e. they can't select 2018-01-01 as well) then uncomment this line below
        /*if ([date isEqualToDate:self.startingDateToAvoid] || [date isEqualToDate:self.endingDateToAvoid]) {
            return NO;
        }*/
        // if the date passed in is between your starting and ending date, we don't want to allow selection
        if ([date compare:self.startingDateToAvoid] == NSOrderedDescending &&
            [date compare:self.endingDateToAvoid] == NSOrderedAscending) {
            return NO;
        }
        return YES;
    }
    
    - (BOOL)calendar:(FSCalendar *)calendar shouldSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition {
        return [self _shouldAllowSelectionOfDate:date];
    }
    
    @end