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

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

.m


#import "LYWCollectionViewCell.h"

@implementation LYWCollectionViewCell

- (instancetype)initWithFrame:(CGRect)frame{
 if (self == [super initWithFrame:frame]) {
 _dateLable = [[UILabel alloc] initWithFrame:self.bounds];
 [_dateLable setTextAlignment:NSTextAlignmentCenter];
 [_dateLable setFont:[UIFont systemFontOfSize:17]];
 _dateLable.textColor = [UIColor blackColor];
 [self addSubview:_dateLable];
 }
 return self;
}
@end

接着代理


//cell大小及间距
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
 return CGSizeMake(ScreenWidth/7, ScreenWidth/7);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
 return UIEdgeInsetsMake(0, 0, 0, 0);
}

既然有日历,总得显示哪年哪月吧,前面已经注册表头视图了,这里只需要实现以下代理方法即可

collectionView有点不同其头视图也有单独的类,和cell一样先自定义headCell,也是非常简单的自定义

.h文件


#import <UIKit/UIKit.h>

@interface LYWCollectionReusableView : UICollectionReusableView

@property (nonatomic,strong) UILabel *dateLable;

- (instancetype)initWithFrame:(CGRect)frame;

@end

.m文件


#import "LYWCollectionReusableView.h"

@implementation LYWCollectionReusableView

- (instancetype)initWithFrame:(CGRect)frame{
 if (self == [super initWithFrame:frame]) {
 _dateLable = [[UILabel alloc] initWithFrame:self.bounds];
 [_dateLable setTextAlignment:NSTextAlignmentLeft];
 [_dateLable setFont:[UIFont systemFontOfSize:20]];
 _dateLable.textColor = [UIColor blackColor];
 [self addSubview:_dateLable];
 }
 return self;
}

@end

接着代理方法,这里也有个三项判断式,和上面的大同小异,主要是防止12月显示为0月


- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
 if (kind == UICollectionElementKindSectionHeader) {
 LYWCollectionReusableView *headerRV = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:headerID forIndexPath:indexPath];
 //自定义蓝色
 headerRV.backgroundColor = DODGER_BLUE;
 NSDate *currentDate = [[NSDate alloc]init];
 NSInteger year = ([currentDate month:currentDate] + indexPath.section)/12 + 2016;
 NSInteger mounth = ([currentDate month:currentDate] + indexPath.section) % 12 == 0 ? 12 : ([currentDate month:currentDate] + indexPath.section)%12;
 headerRV.dateLable.text = [NSString stringWithFormat:@"%ld年%ld月",year,mounth];
 return headerRV;
 }else{
 return nil;
 }
}

还是代理,处理选中效果,选中的为黄色