日历

1.工具类JF_CalendarTools:

.h文件

#import <Foundation/Foundation.h>

@interface JF_CalendarTools : NSObject

+(int)getWeekOfFirstDayOfMonthWithYear:(int)year withMonth:(int)month;
+(int)getDaysOfMonthWithYear:(int)year withMonth:(int)month;
+(int)getYear;
+(int)getMonth;
+(int)getDay;
+(BOOL)isLoopYear:(NSInteger)year;

@end

.m文件

#import "JF_CalendarTools.h"

@implementation JF_CalendarTools
//返回当前年
+(int)getYear{
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSDate *nowDate = [NSDate date];
    NSDateComponents *nowDateComps = [[NSDateComponents alloc] init];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    nowDateComps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:nowDate];
    
    return (int)[nowDateComps year];

}

//返回当前月
+(int)getMonth{
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSDate *nowDate = [NSDate date];
    NSDateComponents *nowDateComps = [[NSDateComponents alloc] init];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    nowDateComps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:nowDate];
    
    return (int)[nowDateComps month];
}

//返回当前日
+(int)getDay{
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSDate *nowDate = [NSDate date];
    NSDateComponents *nowDateComps = [[NSDateComponents alloc] init];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    nowDateComps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:nowDate];
    
    return (int)[nowDateComps day];
}

//获得某个月的第一天是星期几
+(int)getWeekOfFirstDayOfMonthWithYear:(int)year withMonth:(int)month{
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSString *firstWeekDayMonth = [[NSString alloc] initWithFormat:@"%d",year];
    firstWeekDayMonth = [firstWeekDayMonth stringByAppendingString:[[NSString alloc]initWithFormat:@"%s","-"]];
    firstWeekDayMonth = [firstWeekDayMonth stringByAppendingString:[[NSString alloc]initWithFormat:@"%d",month]];
    firstWeekDayMonth = [firstWeekDayMonth stringByAppendingString:[[NSString alloc]initWithFormat:@"%s","-"]];
    firstWeekDayMonth = [firstWeekDayMonth stringByAppendingString:[[NSString alloc]initWithFormat:@"%d",1]];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *weekOfFirstDayOfMonth = [dateFormatter dateFromString:firstWeekDayMonth];
    
    NSDateComponents *newCom = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday fromDate:weekOfFirstDayOfMonth];
    
    return  (int)[newCom weekday] - 1;
}

//返回一个月有多少天
+(int)getDaysOfMonthWithYear:(int)year withMonth:(int)month{
    
    NSInteger days = 0;
    //1,3,5,7,8,10,12
    NSArray *bigMoth = [[NSArray alloc] initWithObjects:@"1",@"3",@"5",@"7",@"8",@"10",@"12", nil];
    //4,6,9,11
    NSArray *milMoth = [[NSArray alloc] initWithObjects:@"4",@"6",@"9",@"11", nil];
    
    if ([bigMoth containsObject:[[NSString alloc] initWithFormat:@"%ld",(long)month]]) {
        days = 31;
    }else if([milMoth containsObject:[[NSString alloc] initWithFormat:@"%ld",(long)month]]){
        days = 30;
    }else{
        if ([self isLoopYear:year]) {
            days = 29;
        }else
            days = 28;
    }
    return (int)days;
}

//判断是否是闰年
+(BOOL)isLoopYear:(NSInteger)year{
    if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
        return true;
    }else
        return NO;
}

@end
2.JF_CalendarCell类:

.h文件

#import <UIKit/UIKit.h>

@interface JF_CalendarCell : UICollectionViewCell

@property(nonatomic,strong) UILabel *numLabel;

@end

.m文件
#import "JF_CalendarCell.h"

@implementation JF_CalendarCell

-(instancetype)initWithFrame:(CGRect)frame{
    self=[super initWithFrame:frame];
    if (self) {
        self.numLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 28, 28)];
       // self.numLabel.backgroundColor=[UIColor grayColor];
        self.numLabel.textAlignment=1;
        self.numLabel.layer.masksToBounds=YES;
        //self.numLabel.layer.borderWidth=1;
        self.numLabel.layer.cornerRadius=28/2;
         // self.numLabel.center=self.center;
        [self addSubview:self.numLabel];
    }
    
    return self;
    
}
@end
3.JF_CalendarView类
.h文件

#import <UIKit/UIKit.h>
#import "JF_CalendarTools.h"

#import "JF_CalendarCell.h"


#define Blue_textColor [UIColor colorWithRed:105/255.0 green:187/255.0 blue:229/255.0 alpha:1.0]
#define Gray_textColor [UIColor colorWithRed:241/255.0 green:241/255.0 blue:241/255.0 alpha:1.0]
@interface JF_CalendarView : UICollectionView<UICollectionViewDataSource,UICollectionViewDelegate>

@property(nonatomic,assign) int year;
@property(nonatomic,assign) int searchYear;

@property(nonatomic,assign) int month;
@property(nonatomic,assign) int searchMonth;


@property(nonatomic,assign) int day;
@property(nonatomic,assign) int searchDay;

@property(nonatomic,assign) int daysOfMonth;
@property(nonatomic,assign) int searchDaysOfMonth;

@property(nonatomic,assign) CGFloat cellWidth;

@property(nonatomic,strong) UIView *headerView;

@property(nonatomic,copy) NSMutableArray *registerArr;

@end

.m文件


#import "JF_CalendarView.h"

@implementation JF_CalendarView

-(NSMutableArray*)registerArr{
    if (!_registerArr) {
#pragma arguments-初始化应该加载本地或者服务器端签到日期,敲到完成上传或者本地存储;
        
        _registerArr=[[NSMutableArray alloc]init];
        
    }
    return _registerArr;
    
}

-(instancetype)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout{
    self=[super initWithFrame:frame collectionViewLayout:layout];
    
    if (self) {
        
        [self registerClass:[JF_CalendarCell class] forCellWithReuseIdentifier:@"cell"];
        self.scrollEnabled=NO;
       // UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc]init];
        //layout.minimumInteritemSpacing=0;
        //
        self.delegate=self;
        self.backgroundColor=[UIColor whiteColor];
        self.dataSource=self;
        //[self registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
        //
        self.year=[JF_CalendarTools getYear];
        self.searchYear=self.year;
        
        self.month=[JF_CalendarTools getMonth];
        self.searchMonth=self.month;
        
        self.day=[JF_CalendarTools getDay];
        self.searchDay=self.day;
        //
        [self.registerArr addObject:[NSString stringWithFormat:@"%.4d%.2d%.2d",self.year,self.month,self.day]];
        
        self.daysOfMonth=[JF_CalendarTools getDaysOfMonthWithYear:self.year withMonth:self.month];
        self.searchDaysOfMonth=self.daysOfMonth;
        
        //
        self.cellWidth=(frame.size.width-8*5)/7;
        //
        [self setHeaderViewWithWidth:frame.size.width];
        //
     //  NSLog(@"%d",[JF_CalendarTools getWeekOfFirstDayOfMonthWithYear:self.year withMonth:self.month]);
        
    }
    return self;
}
-(void)setHeaderViewWithWidth:(CGFloat)width{
    NSArray *a=[NSArray arrayWithObjects:@"日", @"一",@"二",@"三",@"四",@"五",@"六",nil];
    [self.headerView removeFromSuperview];
    self.headerView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, width, 80)];
    //self.headerView.backgroundColor=[UIColor blueColor];
    //
    UIButton *nextButton=[UIButton buttonWithType:UIButtonTypeCustom];
    [nextButton setFrame:CGRectMake(width-90, 10, 20, 20)];
    [nextButton addTarget:self action:@selector(next:) forControlEvents:UIControlEventTouchUpInside];
    [nextButton setImage:[UIImage imageNamed:@"next.png"] forState:UIControlStateNormal];
   // nextButton.backgroundColor=[UIColor blackColor];
    [self.headerView addSubview:nextButton];
    UIButton *preButton=[UIButton buttonWithType:UIButtonTypeCustom];
    [preButton setFrame:CGRectMake(70, 10, 20, 20)];
    [preButton addTarget:self action:@selector(pre:) forControlEvents:UIControlEventTouchUpInside];
    [preButton setImage:[UIImage imageNamed:@"pre.png"] forState:UIControlStateNormal];
   // preButton.backgroundColor=[UIColor blackColor];

    [self.headerView addSubview:preButton];
    //
    UILabel *dateLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 16, 100, 30)];
    dateLabel.textAlignment=1;
    dateLabel.center=CGPointMake(width/2, 20);
    dateLabel.text=[NSString stringWithFormat:@"%d-%.2d",self.searchYear,self.searchMonth];
    [self.headerView addSubview:dateLabel];
    //
    UIView *blueView=[[UIView alloc]initWithFrame:CGRectMake(10, 40, width-20, 35)];
    blueView.backgroundColor=Blue_textColor;
    [self.headerView addSubview:blueView];
    CGFloat labelWidth=(width-35)/7;
    for (int i=0; i<7; i++) {
        UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(i*labelWidth+3, 0, labelWidth, 30)];
        label.text=[a objectAtIndex:i];
        label.textAlignment=1;
        label.textColor=[UIColor whiteColor];
        [blueView addSubview:label];
    }
    [self addSubview:self.headerView];
}
-(void)next:(UIButton*)sender{
    //NSLog(@"next");
    if (self.searchMonth==12) {
        self.searchMonth=1;
        self.searchYear++;
        
    }else{
        self.searchMonth++;
    }
    // self.searchDay=[JF_CalendarTools getDay]
    
    [self setHeaderViewWithWidth:self.frame.size.width];
    [self reloadData];
}
-(void)pre:(UIButton*)sender{
   // NSLog(@"pre");
    if (self.searchMonth==1) {
        self.searchMonth=12;
        self.searchYear--;
        
    }else{
        self.searchMonth--;
    }
    // self.searchDay=[JF_CalendarTools getDay]
    self.searchDaysOfMonth=[JF_CalendarTools getDaysOfMonthWithYear:self.searchYear withMonth:self.searchMonth];
    [self setHeaderViewWithWidth:self.frame.size.width];
    [self reloadData];
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
   // return _datasourceArr.count;
    return 42;
}
//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
//定义每个UICollectionCell 的大小

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //return CGSizeMake((K_Width-5)/4, 130);
    return CGSizeMake(self.cellWidth, self.cellWidth-10);
}
//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    //  UIEdgeInsetsMake(<#CGFloat top#>, <#CGFloat left#>, <#CGFloat bottom#>, <#CGFloat right#>)
    return UIEdgeInsetsMake(80, 17.5, 1, 17.5);
    
}
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    JF_CalendarCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    int dateNum=(int)indexPath.row-[JF_CalendarTools getWeekOfFirstDayOfMonthWithYear:self.searchYear withMonth:self.searchMonth]+1;
    
/*
统一日期设置
*/
        //月内
        if (dateNum>=1&&(indexPath.row<self.searchDaysOfMonth+[JF_CalendarTools getWeekOfFirstDayOfMonthWithYear:self.searchYear withMonth:self.searchMonth])) {
            cell.numLabel.text=[NSString stringWithFormat:@"%d",dateNum];
            cell.numLabel.textColor=[UIColor blackColor];

        }
    
        //前一个月
        if (dateNum<1) {
           // cell.numLabel.text=@"";
            cell.numLabel.textColor=[UIColor grayColor];

            int days;
            if (self.searchMonth!=1) {
                days=[JF_CalendarTools getDaysOfMonthWithYear:self.searchYear withMonth:self.searchMonth-1];
            }else if(self.searchMonth==1){
                days=[JF_CalendarTools getDaysOfMonthWithYear:self.searchYear-1 withMonth:12];
            }
             cell.numLabel.text=[NSString stringWithFormat:@"%d",dateNum+days];
        }
    
        //后一个月
        if (dateNum>self.searchDaysOfMonth) {
            cell.numLabel.text=[NSString stringWithFormat:@"%d",dateNum-self.searchDaysOfMonth];
            cell.numLabel.textColor=[UIColor grayColor];

        }
/*
背景颜色设置
*/
    //当前月
    if ([NSString stringWithFormat:@"%d%.2d",self.year,self.month].intValue==[NSString stringWithFormat:@"%d%.2d",self.searchYear,self.searchMonth].intValue) {
        cell.numLabel.backgroundColor=[UIColor whiteColor];
        cell.numLabel.layer.masksToBounds=YES;
        cell.numLabel.layer.borderColor=[UIColor grayColor].CGColor;
        cell.numLabel.layer.borderWidth=0;
        //月内
        if (dateNum>=1&&(dateNum<=self.searchDay)) {
            cell.numLabel.backgroundColor=Gray_textColor;
            cell.numLabel.text=[NSString stringWithFormat:@"%d",dateNum];
            
            cell.numLabel.layer.borderWidth=1;

        }
        
    }
    //之后的月
    if ([NSString stringWithFormat:@"%d%.2d",self.year,self.month].intValue<[NSString stringWithFormat:@"%d%.2d",self.searchYear,self.searchMonth].intValue) {
       // NSLog(@"大于");
        cell.numLabel.layer.masksToBounds=YES;
        cell.numLabel.layer.borderColor=[UIColor grayColor].CGColor;
        cell.numLabel.layer.borderWidth=0;
         cell.numLabel.backgroundColor=[UIColor whiteColor];
    }
    //之前的月
    if ([NSString stringWithFormat:@"%d%.2d",self.year,self.month].intValue>[NSString stringWithFormat:@"%d%.2d",self.searchYear,self.searchMonth].intValue) {
        //NSLog(@"小于");

        cell.numLabel.layer.masksToBounds=YES;
        cell.numLabel.layer.borderColor=[UIColor grayColor].CGColor;
        cell.numLabel.layer.borderWidth=0;
        cell.numLabel.backgroundColor=[UIColor whiteColor];
        //月内
        if (dateNum>=1&&(indexPath.row<self.searchDaysOfMonth+[JF_CalendarTools getWeekOfFirstDayOfMonthWithYear:self.searchYear withMonth:self.searchMonth])) {
            cell.numLabel.backgroundColor=Gray_textColor;
            
            cell.numLabel.text=[NSString stringWithFormat:@"%d",dateNum];
            cell.numLabel.layer.borderWidth=1;

        }
    }
/*
设置签到颜色
*/
    
#pragma arguments-数组内包含当前日期则说明此日期签到了,设置颜色为蓝色;
    if([self.registerArr containsObject:[NSString stringWithFormat:@"%.4d%.2d%.2d",self.searchYear,self.searchMonth,dateNum]]){
        //NSLog(@"blue");
        cell.numLabel.backgroundColor=Blue_textColor;
        cell.numLabel.textColor=[UIColor whiteColor];
        cell.numLabel.layer.masksToBounds=YES;
        cell.numLabel.layer.borderColor=[UIColor grayColor].CGColor;
        cell.numLabel.layer.borderWidth=0;
    }
    //NSLog(@"%d",[NSString stringWithFormat:@"%d%.2d",self.searchYear,self.searchMonth].intValue);
    return cell;
    
}
/*
//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{

    
   
}
*/
//返回这个UICollectionView是否可以被选择
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}


@end

4.效果图:

初探佳境,多多学习交流
原文地址:https://www.cnblogs.com/sunjianfei/p/5508826.html