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

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


#import "ViewController.h"
#import "Macro.h"
#import "NSDate+LYWCalendar.h"
#import "LYWCollectionViewCell.h"
#import "LYWCollectionReusableView.h"

定义一些全局变量


static NSString *cellID = @"cellID";
static NSString *headerID = @"headerID";
static NSString *footerID = @"footerID";

@implementation ViewController
{
 //自动布局
 UICollectionViewFlowLayout *_layout;
 //表格视图
 UICollectionView *_collectionView;
 //当月第一天星期几
 NSInteger firstDayInMounthInWeekly;
 NSMutableArray *_firstMounth;
 //容纳六个数组的数组
 NSMutableArray *_sixArray;
 
}


//定义星期视图,若为周末则字体颜色为绿色
 self.automaticallyAdjustsScrollViewInsets = NO;//关闭自动适应
 NSArray *weekTitleArray = @[@"周日",@"周一",@"周二",@"周三",@"周四",@"周五",@"周六"];
 for (int i = 0; i < weekTitleArray.count; i++) {
 UILabel *weekTitleLable = [[UILabel alloc]initWithFrame:CGRectMake(i * ((ScreenWidth/(weekTitleArray.count))), 64, ScreenWidth/(weekTitleArray.count ), 30)];
 if (i == 0 || i == 6) {
  weekTitleLable.textColor = [UIColor greenColor];
 }else{
  weekTitleLable.textColor = [UIColor blackColor];
 }
 weekTitleLable.text = [weekTitleArray objectAtIndex:i];
 weekTitleLable.textAlignment = NSTextAlignmentCenter;
 [self.view addSubview:weekTitleLable];
}

//设置collectionView及自动布局,代理方法尤为重要
 _layout = [[UICollectionViewFlowLayout alloc]init];
 //头部始终在顶端
 _layout.sectionHeadersPinToVisibleBounds = YES;
 //头部视图高度
 _layout.headerReferenceSize = CGSizeMake(414, 40);
 _layout.minimumLineSpacing = 0;
 _layout.minimumInteritemSpacing = 0;
 _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 64 + 30, ScreenWidth, ScreenHeight - 64 - 30) collectionViewLayout:_layout];
 _collectionView.backgroundColor = [UIColor whiteColor];
 //注册表格
 [_collectionView registerClass:[LYWCollectionViewCell class] forCellWithReuseIdentifier:cellID];
 //注册头视图
 [_collectionView registerClass:[LYWCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerID];
 //注册尾视图
// [_collectionView registerClass:[UICollectionReusableView class] forCellWithReuseIdentifier:footerID];
   _collectionView.delegate = self;
 _collectionView.dataSource = self;
 [self.view addSubview:_collectionView];

逻辑部分,这里有个比较长的三项表达式

(daysInMounth > 29 && (firstDayInThisMounth == 6 || firstDayInThisMounth ==5) ? 42 : 35)

就是日历到底是六行还是七行,这就要根据日历的特性来判断了,如果当月天数大于29天并且当月第一天星期六(以这个程序的准则)或者星期天是返回六行剩下的返回三行,也有可能返回四行的,但是就这个程序来说是不可能的也就不需要做判断了