Calendar_Demo(日历)

#import<UIKit/UIKit.h>
#import<QuartzCore/QuartzCore.h>
@protocol CalendarDelegate<NSObject>
-(void)clickedCanlendarButton;
@end

@interface Calendar : UIView{
CFGregorianDatecurrentMonthDate;
CFAbsoluteTimecurrentTime;
UIImageView *viewImageView;
UIView *topView;
NSString *daydata;
NSString *saveMonthDate;
NSString *selectDay;
intupMonthDaycounts;
BOOLisContinuousClick;
int saveTodaytag;
}


@property(nonatomic,retain) NSString *selectDay;
@property    BOOLisContinuousClick;
@property CFGregorianDatecurrentMonthDate;
@propertyCFAbsoluteTime   currentTime;
@property(nonatomic, retain)   UIImageView    *viewImageView;
@property (nonatomic, retain) id<CalendarDelegate>delegate;
-(int)getMonthWeekday:(CFGregorianDate)date;
-(int)getDayCountOfaMonth:(CFGregorianDate)date;
-(void)drawTopWeekDay;
-(void)drawDateWords;
-(void)movePrevMonth;
-(void)moveNextMonth;
-(void)movePrevOrNextMonth:(int)isPrev;
-(void)myInit;
-(void)drawGirdLines;
-(void)dateButtonClicked:(UIButton *)buttontag;
//-(void)selectCalenda
@end
////////////////////////////////////////////////////////////////
.m

#import "Calendar.h"
@implementation Calendar
@synthesizecurrentMonthDate;
@synthesize currentTime;
@synthesize viewImageView;
@synthesize delegate;
@synthesizeisContinuousClick;
@synthesize selectDay;

int yearButtonFontSize;
int weekFontSize;
int calendarWidth;
int calendarHeight;
int yearMonthFontSize;
int calendarFontSize;
int _height;
-(void)myInit
{
calendarWidth=320;//日历宽
calendarHeight=480;//日历高
 
weekFontSize=15;//星期字体大小设置
yearMonthFontSize=24;//年月标题字体大小设置
yearButtonFontSize=15;//切换上下月按钮的字体的大小
 
_height=calendarHeight/10;
 
calendarFontSize=16;//日期字体大小
}
-(id)initWithFrame:(CGRect)frame
{
self= [super initWithFrame:frame];
    if (self) {
isContinuousClick=YES;
currentTime=CFAbsoluteTimeGetCurrent();
currentMonthDate=CFAbsoluteTimeGetGregorianDate(currentTime,CFTimeZoneCopyDefault());
currentMonthDate.day=1;
 
NSDateFormatter *nowyearmonthday=[[NSDateFormatteralloc] init];
[nowyearmonthday setDateFormat:@"yyyy-MM-d"];
saveMonthDate=[[NSStringalloc]initWithString:[nowyearmonthdaystringFromDate:[NSDatedate]]];
[nowyearmonthday release];
NSLog(@"saveMonthDate==%@",saveMonthDate);
       [selfmyInit];
[self drawTopWeekDay];
[self drawDateWords];
 
[self setFrame:CGRectMake(0,0, 320, calendarHeight)];
[self setBackgroundColor:[UIColor clearColor]];
 
    }
return self;
}
-(void)drawTopWeekDay
{
 
    int width=calendarWidth/7;
 
//    //返回上个月按钮
    UIButton *prevMonth = [[UIButton alloc] init];  
prevMonth.frame=CGRectMake(0,0, calendarWidth/6,_height);
[prevMonth setTitle:@"上个月"forState:UIControlStateNormal];
[prevMonth.titleLabel setFont:[UIFont boldSystemFontOfSize:yearButtonFontSize]];
[prevMonth setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[prevMonth addTarget:selfaction:@selector(movePrevMonth) forControlEvents:UIControlEventTouchUpInside];    [self addSubview:prevMonth]; //年月标题 NSString *yearMonth=[[NSString alloc]initWithFormat:@"%i年%i月",currentMonthDate.year,currentMonthDate.month]; UILabel *yearMonthLabel=[[UILabel alloc]initWithFrame:CGRectMake(calendarWidth/6,0, calendarWidth/6*4, _height)];yearMonthLabel.textAlignment=UITextAlignmentCenter;yearMonthLabel.textColor=[UIColor blackColor];yearMonthLabel.backgroundColor=[UIColor clearColor];    yearMonthLabel.text=yearMonth;yearMonthLabel.font =[UIFont systemFontOfSize:yearMonthFontSize];    [self addSubview:yearMonthLabel];      [yearMonth release];    [yearMonthLabel release]; //    //查看下个月按钮      UIButton *nextMonth = [[UIButton alloc] init];[nextMonth setTitle:@"下个月"forState:UIControlStateNormal];[nextMonth.titleLabel setFont:[UIFont boldSystemFontOfSize:yearButtonFontSize]];[nextMonth setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];nextMonth.frame=CGRectMake(calendarWidth/6*5, 10, calendarWidth/6, _height);[nextMonth addTarget:selfaction:@selector(moveNextMonth) forControlEvents:UIControlEventTouchUpInside];    [self addSubview:nextMonth];  //   //    //星期标题 NSArray *weekDay=[[NSArray alloc]initWithObjects:@"周日",@"周一",@"周二",@"周三",@"周四",@"周五",@"周六", nil];       for (int i = 0; i < 7; i++) { UILabel *weekLabel=[[UILabel alloc]initWithFrame:CGRectMake(i*width, _height, width, _height)];weekLabel.backgroundColor =[UIColor clearColor];weekLabel.textAlignment=UITextAlignmentCenter;[weekLabelsetFont:[UIFontboldSystemFontOfSize:weekFontSize]];weekLabel.textColor=[UIColor blackColor];       if (i == 0|| i == 6) {          weekLabel.textColor=[UIColor redColor];       }                     weekLabel.text=[weekDay objectAtIndex:i];       [selfaddSubview:weekLabel];       [weekLabel release];    }    [weekDay release];}-(void)drawDateWords{       float headHeight=calendarHeight/5;    float itemHeight=40; intcurrentMonthDaycounts=[self getDayCountOfaMonth:currentMonthDate]; intcurrentWeekday=[self getMonthWeekday:currentMonthDate]%7;    NSLog(@"currentWeekday==%d",currentWeekday);    int day=0;    int x = 0;    int y = 0;    int width=calendarWidth/7; NSDateFormatter *dateFormatteryy = [[NSDateFormatteralloc] init]; NSDateFormatter *dateFormattermm = [[NSDateFormatteralloc] init]; NSDateFormatter *dateFormatterdd = [[NSDateFormatteralloc] init];    [dateFormatteryy setDateFormat:@"yyyy"];    [dateFormattermm setDateFormat:@"M"];    [dateFormatterdd setDateFormat:@"d"]; NSString *nowyear = [[NSString alloc] initWithString:[dateFormatteryystringFromDate:[NSDatedate]]]; NSString *nowmonth = [[NSString alloc] initWithString:[dateFormattermmstringFromDate:[NSDatedate]]]; NSString *tody = [[NSString alloc] initWithString:[dateFormatterddstringFromDate:[NSDatedate]]];    NSLog(@"nowmonth==%@",nowmonth);    NSLog(@"tody==%@",tody); NSString *year=[[NSString alloc]initWithFormat:@"%i",currentMonthDate.year]; NSString *month =[[NSString alloc]initWithFormat:@"%i",currentMonthDate.month];    for (int i = 0 ; i <currentWeekday; i++) { NSString *date=[[NSString alloc]initWithFormat:@"%i",i+upMonthDaycounts-currentWeekday+1];             UIButton*button = [[UIButtonalloc] init];       button.frame=CGRectMake((i%7)*width +4,(i/7)*itemHeight+headHeight + 4, width-5,itemHeight-6);      [buttonsetTitle:dateforState:UIControlStateNormal];[buttonsetTitleColor:[UIColorgrayColor] forState:UIControlStateNormal];button.backgroundColor= [UIColorcolorWithRed:0.847green:0.847 blue:0.847 alpha:1.0]; [button.titleLabelsetFont:[UIFontboldSystemFontOfSize:calendarFontSize]];        [selfaddSubview:button];       [button release];        }      for (int i = 0;i<currentMonthDaycounts; i++) {       day=i+currentWeekday;       x=day%7;       y=day/7;       NSString *date=[[NSString alloc]initWithFormat:@"%i",i+1];             UIButton*button = [[UIButtonalloc] init];       button.tag=i+1; //       [buttonsetBackgroundImage:[UIImage imageNamed:@"date.png"]forState:UIControlStateNormal];       button.frame=CGRectMake(x*width +5,y*itemHeight+headHeight + 4, width-6,itemHeight-7);      [buttonsetTitle:dateforState:UIControlStateNormal];[buttonsetTitleColor:[UIColorblackColor]forState:UIControlStateNormal];button.backgroundColor= [UIColorcolorWithRed:0.847green:0.847 blue:0.847 alpha:1.0]; [button.titleLabelsetFont:[UIFontboldSystemFontOfSize:calendarFontSize]]; [buttonaddTarget:self action:@selector(dateButtonClicked:) forControlEvents:UIControlEventTouchUpInside];        if ([dateisEqualToString:tody]&& [nowyear isEqualToString:year]&& [nowmonth isEqualToString:month]) {saveTodaytag=button.tag;           [buttonsetHighlighted:YES];button.backgroundColor = [UIColor colorWithRed:1 green:0.63 blue:0.91 alpha:0.99];[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];       }       [selfaddSubview:button];       [button release];    }     if((currentMonthDaycounts+currentWeekday)%7!=0) {       intnextMonthDaycounts=((currentMonthDaycounts+currentWeekday)/7+1)*7;        for(int i =currentMonthDaycounts+currentWeekday; i <nextMonthDaycounts; i ++) {           NSString *date=[[NSString alloc]initWithFormat:@"%i",i-(currentMonthDaycounts+currentWeekday)+1];                UIButton *button =[[UIButton alloc] init];           button.frame=CGRectMake((i%7)*width +4,(i/7)*itemHeight+headHeight + 4, width-5,itemHeight-6);      [button setTitle:date forState:UIControlStateNormal];[button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];          button.backgroundColor =[UIColor colorWithRed:0.847 green:0.847 blue:0.847 alpha:1.0]; [button.titleLabel setFont:[UIFont boldSystemFontOfSize:calendarFontSize]];           [self addSubview:button];           [buttonrelease];       } }     [tody release];    [nowyear release];    [nowmonth release];    [year release];    [month release];    [dateFormatteryy release];    [dateFormattermm release];    [dateFormatterdd release]; }-(int)getDayCountOfaMonth:(CFGregorianDate)date{     switch (date.month) {       case 1:          upMonthDaycounts=31;          break;       case 2:          upMonthDaycounts=31;          break;       case 3:          if (date.year%4==0&&date.year!=0){               upMonthDaycounts=29;          }else{              upMonthDaycounts=28;           }          break;       case 4:          upMonthDaycounts=31;          break;       case 5:          upMonthDaycounts=30;          break;       case 6:          upMonthDaycounts=31;          break;       case 7:          upMonthDaycounts=30;          break;       case 8:          upMonthDaycounts=31;          break;       case 9:          upMonthDaycounts=31;          break;       case 10:          upMonthDaycounts=30;          break;       case 11:          upMonthDaycounts=31;          break;       case 12:          upMonthDaycounts=30;          break;       default:          break;    }    switch (date.month) {       case 1:       case 5:       case 7:       case 8:       case 10:       case 12:       case 3:          return 31;       case 2:          upMonthDaycounts=31;          if (date.year%4==0&&date.year!=0){               return 29;          }else{              return 28;           }       case 4:       case 6:       case 9:       case 11:          return 30;       default:          return 31;    }}-(int)getMonthWeekday:(CFGregorianDate)date{ CFTimeZoneRef tz = CFTimeZoneCopyDefault();//获得默认时区    CFGregorianDate month_date;    month_date.year=date.year;    month_date.month=date.month;    month_date.day=1;    month_date.hour=1;    month_date.minute=0;    month_date.second=1;   return (int)CFAbsoluteTimeGetDayOfWeek(CFGregorianDateGetAbsoluteTime(month_date, tz), tz);}-(void)movePrevOrNextMonth:(int)isPrev{ intwidth=calendarWidth;    int posX;    if (isPrev==1) {       posX=width;    }else{       posX=-width;    }     UIImage *viewImage; UIGraphicsBeginImageContext(self.bounds.size);[self.layer renderInContext:UIGraphicsGetCurrentContext()];viewImage=UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); if(viewImageView==nil){viewImageView=[[UIImageViewalloc]initWithImage:viewImage];viewImageView.center=self.center;[[self superview] addSubview:viewImageView];    }else{       viewImageView.image=viewImage;    } viewImageView.hidden=NO; viewImageView.transform=CGAffineTransformMakeTranslation(0,0);    [self setHidden:YES];[selfsetNeedsDisplay]; self.transform=CGAffineTransformMakeTranslation(posX,0);    self.hidden=NO;    for (UIButton *button in self.subviews) {       if( [buttonisKindOfClass:[UIButton class]] )                {                    [buttonremoveFromSuperview];        }    }    for (UILabel *button in self.subviews) {       if( [buttonisKindOfClass:[UILabel class]] )                {                    [buttonremoveFromSuperview];        }    } [selfdrawDateWords];[selfdrawTopWeekDay];[UIView beginAnimations:nilcontext:nil];[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];[UIView setAnimationDuration:0.5]; self.transform=CGAffineTransformMakeTranslation(0,0); viewImageView.transform=CGAffineTransformMakeTranslation(-posX,0);[UIView commitAnimations]; }-(void)movePrevMonth{ if(currentMonthDate.month>1) {currentMonthDate.month-=1;    }else{currentMonthDate.month=12;currentMonthDate.year-=1;    } [selfmovePrevOrNextMonth:0];}-(void)moveNextMonth{ if(currentMonthDate.month<12) {currentMonthDate.month+=1;    }else{currentMonthDate.month=1;currentMonthDate.year+=1;    } [selfmovePrevOrNextMonth:1];}-(void)drawRect:(CGRect)rect{ [selfdrawGirdLines]; }-(void)changeButtonColor:(UIButton *)button{ }-(void)dateButtonClicked:(UIButton *)buttontag{ // NSString *clickedDay=[[NSString alloc]initWithFormat:@"%@",buttontag.tag]; if (currentMonthDate.month<10) {selectDay=[[NSStringalloc]initWithFormat:@"%i-0%i-%i",currentMonthDate.year,currentMonthDate.month,buttontag.tag];}else {selectDay=[[NSStringalloc]initWithFormat:@"%i-%i-%i",currentMonthDate.year,currentMonthDate.month,buttontag.tag];} if(isContinuousClick) {       if(buttontag.alpha==1.0) {if (![selectDay isEqualToString: saveMonthDate]) { [buttontagsetTitleColor:[UIColorwhiteColor]forState:UIControlStateNormal];buttontag.backgroundColor =[UIColor colorWithRed:0.29 green:0.63 blue:0.91 alpha:1.0];       buttontag.alpha=0.9;}       }else{[buttontag setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];          buttontag.backgroundColor =[UIColor colorWithRed:0.847 green:0.847 blue:0.847 alpha:1.0];          buttontag.alpha=1.0;       }    }else {for (UIButton *button in self.subviews) {if ([button isKindOfClass:[UIButton class]]) {if (button.alpha!=1.0&&button.tag>0){[buttonsetTitleColor:[UIColorblackColor]forState:UIControlStateNormal];button.backgroundColor= [UIColorcolorWithRed:0.847green:0.847 blue:0.847 alpha:1.0];button.alpha=1.0;           }}}if (buttontag.tag!=saveTodaytag) {[buttontagsetTitleColor:[UIColorwhiteColor]forState:UIControlStateNormal];buttontag.backgroundColor =[UIColor colorWithRed:0.29 green:0.63 blue:0.91 alpha:1.0];       buttontag.alpha=0.9; }}[delegate clickedCanlendarButton];[selectDay release]; }-(void)drawGirdLines{     float headHeight=calendarHeight/5;    float itemHeight=40;  CGContextRef ctx=UIGraphicsGetCurrentContext();  intwidth=calendarWidth;    int row_Count; if(([self getDayCountOfaMonth:currentMonthDate]+[selfgetMonthWeekday:currentMonthDate])%7==0) {row_Count=([selfgetDayCountOfaMonth:currentMonthDate]+[selfgetMonthWeekday:currentMonthDate]%7)/7;    }else{row_Count=([self getDayCountOfaMonth:currentMonthDate]+[selfgetMonthWeekday:currentMonthDate]%7)/7+1;    }     int s_width=width/7;    inttabHeight=row_Count*itemHeight+headHeight;  CGContextSetGrayStrokeColor(ctx, 0,1);   CGContextMoveToPoint   (ctx,0,headHeight);   CGContextAddLineToPoint   (ctx,0,tabHeight);   CGContextStrokePath       (ctx);   CGContextMoveToPoint   (ctx,width,headHeight);   CGContextAddLineToPoint   (ctx,width,tabHeight);   CGContextStrokePath       (ctx);     for(inti=1;i<8;i++){CGContextSetGrayStrokeColor(ctx,1,1);       CGContextMoveToPoint(ctx, i*s_width-1,headHeight);       CGContextAddLineToPoint( ctx,i*s_width-1,tabHeight);CGContextStrokePath(ctx); CGContextSetGrayStrokeColor(ctx,0.3,1);       CGContextMoveToPoint(ctx, i*s_width+2,headHeight);       CGContextAddLineToPoint( ctx,i*s_width+2,tabHeight);CGContextStrokePath(ctx);    }     for(inti=0;i<row_Count+1;i++){CGContextSetGrayStrokeColor(ctx,1,1);       CGContextMoveToPoint(ctx, 0,i*itemHeight+headHeight+3);       CGContextAddLineToPoint( ctx,width,i*itemHeight+headHeight+3);CGContextStrokePath(ctx); CGContextSetGrayStrokeColor(ctx,0.3,1);       CGContextMoveToPoint(ctx, 0,i*itemHeight+headHeight);       CGContextAddLineToPoint( ctx,width,i*itemHeight+headHeight);CGContextStrokePath(ctx);    } }-(void)dealloc{[saveMonthDaterelease];    [super dealloc];}@endhttp://blog.sina.com.cn/s/blog_796ffec50100tmah.html

posted @ 2015-12-28 14:28  Bo-tree  阅读(244)  评论(0)    收藏  举报