Saturday, 22 February 2014

Custom calendar view in IOS



How to create custom calendar view in iOS - tutorial

Custom Calendar in IOS SDK

Introduction

In this post i am going to tell you, how we can create a calendar  programmatically in IOS/iPhone/objective C.

There are so many open source calendar libraries available on web which you can use in your app.

One day i got the requirement of integrating calendar in my app, a customized one. First, I searched through web for open calendar libraries and came across so many. But then i thought why not go for simple methods to create calendar rather then using open source libraries. In this post i will tell you, about my experience in creating calendar without using open source libraries.


Implementation of code

Creating dateFormatter using NSDateFormatter

The first thing we need to get started is our dateFormatter method as it is going to be used a lot in creating calendar.

Below is the method that create a datFormatter with format dd/MM/yyyy



    
- (NSDateFormatter *)returnDateFormatter {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"dd/MM/yyyy"];
    return dateFormatter;

}


Calculate number of days in a month

Now as our dateFormatter is set, we need to calculate number of days exists for a particular month.
We can get number of days in a month by using below method



    
-(int)numberOfdaysinMonth:(int)selectedMonthNumber WithDate:(NSDate *)selectedDate
{
    NSCalendar* cal = [NSCalendar currentCalendar];
    NSDateComponents* comps = [[NSDateComponents alloc] init];
    // Set your month here
    [comps setMonth:selectedMonthNumber];
    
    NSRange range = [cal rangeOfUnit:NSCalendarUnitDay
                              inUnit:NSCalendarUnitMonth
                             forDate:selectedDate];
    NSLog(@"%lu", (unsigned long)range.length);
    return (int)range.length;
}


In the above method we need to pass selected month as number like 1 for january , 2 for february etc. and current date or selected date.The above method will return us number of days in month.

As we got number of days for a particular month, now we need to know starting day of the month.

Getting first week day for the month

Now we need to get weekDay of starting month, for this we will use NSCalendar APIBelow is the code that give us weekday. i.e 1 = Sunday. 2 = Monday and so on 



    
-(long)weekDayForDate:(NSDate *)date
{
    NSCalendar* cal = [NSCalendar currentCalendar];
    NSDateComponents* comp = [cal components:NSCalendarUnitWeekday fromDate:date];
    return [comp weekday];
    
}


 TIP:- To get first day of month i passed 1 as date.

Drawing out UILabels and UIButtons on Scroll

At this point we got all our requirement to create a calendar month. We have number of days in a monthand first day name and its positionNow we will lay down our scroll view for the month using below method



    
-(void)createButtonsAndLablesForNumberOfDays:(int)days withStartingAtDay:(int)startIndex
{
 for (UIView *v  in [calendarScroll subviews])
    {
        [v removeFromSuperview];
    }
    int xpos = 0;
    int ypos = 0;
    for (int xcount =1; xcount<=7; xcount++)
    {
        if (xcount==startIndex)
        {
            break;
        }
        xpos = xpos+46;
    }
    
    for (int i = 1; i<=days; i++)
    {
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(xpos+5, ypos-5, 46, 33)];
        label.text=[NSString stringWithFormat:@"%d",i];
        label.font=[UIFont boldSystemFontOfSize:14.0];
        label.textColor=[UIColor colorWithRed:87/255.0 green:212/255.0 blue:218/255.0 alpha:1.0];
        [calendarScroll addSubview:label];
        
        
        UIButton *dateButton = [UIButton buttonWithType:UIButtonTypeCustom];
        dateButton.frame = CGRectMake(xpos, ypos, 46, 33);
        
        
        //compare date to place marker over current date
        NSString *actualDate = [[NSString alloc]initWithFormat:@"%d/%d/%d",i,month,year];
        NSDate *date = [[self  returnDateFormatter] dateFromString:actualDate];
        NSString *todayDatestr= [[self returnDateFormatter] stringFromDate:[NSDate date]];
        NSDate *todayDate = [[self returnDateFormatter]dateFromString:todayDatestr];
        NSComparisonResult result = [date compare:todayDate];
        // compare date with today date to display current date
        if (result==NSOrderedSame)
        {
            [dateButton setImage:[UIImage imageNamed:@"dia_over.png"] forState:UIControlStateNormal];
            
        }
        dateButton.tag=i;
        [dateButton addTarget:self action:@selector(dateSelected:) forControlEvents:UIControlEventTouchUpInside];
        [calendarScroll addSubview:dateButton];
        xpos=xpos+46;
        startIndex=startIndex+1;
        
        if (startIndex==8)
        {
            xpos=0;
            ypos=ypos+33;
            startIndex=1;
        }
        
    }
    
}

Final comments

Below is a small chunk of code that will create a calendar month for february 2014


    int month = 2;
    int year = 2014;
    NSDate *date = [[self returnDateFormatter] dateFromString:[NSString stringWithFormat:@"1/%d/%d",month,year]
                    ];
    int numberOfDays = [self numberOfdaysinMonth:month WithDate:date];
    int index =  [self weekDayForDate:date];

    [self createButtonsAndLablesForNumberOfDays:numberOfDays withStartingAtDay:index];

   

Note: ScrollView is not created programmatically and is taken as outlet in xib.


1 comment:
Write comments
  1. easy and great tutorial for creating calendar in IOS SDK programmatically.

    ReplyDelete