iOS自定义日历控件的简单实现过程

2020-01-18 16:17:07王振洲

 


 //NumberMounthes 为宏定义,表示要显示月的个数,程序要求是六个月,所以宏定义为六
  //#define NumberMounthes 6 //想要展示的月数

//创建六个数组,并将这六个数组装入大数组中
 _sixArray = [[NSMutableArray alloc]init];
 for (int i = 0; i < NumberMounthes ; i++ ) {
 NSMutableArray *array = [[NSMutableArray alloc]init];
 [_sixArray addObject:array];
 }
 //为六个数组写入每个月的日历信息
 for (int i = 0 ; i < NumberMounthes; i++) {
 //获取月份
 int mounth = ((int)[currentDate month:currentDate] + i)%12;
 NSDateComponents *components = [[NSDateComponents alloc]init];
 //获取下个月的年月日信息,并将其转为date
 components.month = mounth;
 components.year = 2016 + mounth/12;
 components.day = 1;
 NSCalendar *calendar = [NSCalendar currentCalendar];
 NSDate *nextDate = [calendar dateFromComponents:components];
 //获取该月第一天星期几
 NSInteger firstDayInThisMounth = [nextDate firstWeekdayInThisMonth:nextDate];
 //该月的有多少天daysInThisMounth
 NSInteger daysInThisMounth = [nextDate totaldaysInMonth:nextDate];
 NSString *string = [[NSString alloc]init];
 for (int j = 0; j < (daysInMounth > 29 && (firstDayInThisMounth == 6 || firstDayInThisMounth ==5) ? 42 : 35) ; j++) {
  if (j < firstDayInThisMounth || j > daysInThisMounth + firstDayInThisMounth - 1) {
  string = @"";
  [[_sixArray objectAtIndex:i]addObject:string];
  }else{
  string = [NSString stringWithFormat:@"%ld",j - firstDayInThisMounth + 1];
  [[_sixArray objectAtIndex:i]addObject:string];
  }
 }
 }

下面是代理方法


//这两个不用说,返回cell个数及section个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
 return [[_sixArray objectAtIndex:section] count];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
 return _sixArray.count;
}


//这里是自定义cell,非常简单的自定义
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
 LYWCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
 UIView *blackgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height)];
 blackgroundView.backgroundColor = [UIColor yellowColor];
 cell.dateLable.text = [[_sixArray objectAtIndex:indexPath.section]objectAtIndex:indexPath.row];
 NSDate *date = [[NSDate alloc]init];
 NSInteger day = [date day:date];
  //设置单击后的颜色
   cell.selectedBackgroundView = blackgroundView;
 return cell;
}

自定义cell  .h


#import <UIKit/UIKit.h>

@interface LYWCollectionViewCell : UICollectionViewCell

@property (nonatomic,strong) UILabel *dateLable;

- (instancetype)initWithFrame:(CGRect)frame;

@end