iOS 简单日历表

日历.gif

首先谈谈组成

整体是个CollectionView,每个月就是一个section,XXXX年XX月和周一到周日部分是每个分组的Header,每个分组其实有42个Item,如果是当月的Item显示号数和副标题,如果不是当月的Item显示空字符串并且隐藏当天的副标题


接下来是实现

5BD21078-8845-4698-BCB7-57D3655C2128.png

第一步 创建CalendarDateModel继承自NSObject

#import <Foundation/Foundation.h>

@interface CalendarDateModel : NSObject

@property (nonatomic, copy)NSString *day;//当天的号数 如果非当月为空字符串

@property (nonatomic, assign)BOOL isPast;//用于在第一个月判断是否是过的天数
//可以根据需求添加需要的属性 这个model就是存储在Item上需要显示的信息
@end

第二步 创建CalendarDateManager 该类用于管理数据源 如果有网络请求可以加在这里

.h

#import <Foundation/Foundation.h>
#import "CalendarDateModel.h"
@interface CalendarDateManager : NSObject
- (NSArray *)getDateArray;
@end

.m

#import "CalendarDateManager.h"

@interface CalendarDateManager (){
    
    NSMutableArray *_dateArray;
    
}

@property (nonatomic, strong)NSDateFormatter *formatter;

@end

@implementation CalendarDateManager

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self initDateArray];
    }
    return self;
}

- (NSArray *)getDateArray{
    return _dateArray.copy;
}

- (void)initDateArray{
    
    NSDate *date = [NSDate new];//获取当前时间
    
    NSInteger toDay = [self day:date];//获取当天是几号
    
    _dateArray = [NSMutableArray arrayWithCapacity:6];//这里写死了一次创建6个月 可以根据需要改变 或者可以写一个传创建几个月参数的初始化函数
    
    for (int i = 0; i < 6; i++) { //循环6次 (6个月)

        NSMutableArray *tmpArray = [NSMutableArray arrayWithCapacity:42];
     
        NSInteger daysInThisMonth = [self totaldaysInThisMonth:date];
        NSInteger firstWeekday = [self firstWeekdayInThisMonth:date];
        
        for (NSInteger day = 0; day < 43; day++) {
            
            CalendarDateModel *model = [CalendarDateModel new];
            
            if (day < firstWeekday) {
                model.day = @"";
            }else if (day > firstWeekday + daysInThisMonth - 1){
                model.day = @"";
            }else{
                
                if (i == 0) {//只判断第一个月的天数是否是过去  后面几个月没必要判断
                    
                    if (day - firstWeekday + 1 < toDay) {
                        model.isPast = YES;
                    }//else不用判断 默认NO
                    
                }
                
                model.day = [NSString stringWithFormat:@"%ld", day - firstWeekday + 1];
            }
            
            [tmpArray addObject:model];
        }
    
        NSDictionary *dic = @{@"date":[self.formatter stringFromDate:date], @"itemList":tmpArray};
        
        [_dateArray addObject:dic];
    
        date = [self nextMonth:date];
        
    }
    
}

- (NSDateFormatter *)formatter{
    
    if (!_formatter) {
        _formatter = [[NSDateFormatter alloc] init];
        _formatter.locale = [NSLocale localeWithLocaleIdentifier:@"zh_CN"];
        [_formatter setDateFormat:@"yyyy-MM"];
    }
    return _formatter;
}
#pragma mark- 返回下个月的date
- (NSDate*)nextMonth:(NSDate *)date{
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.month = +1;
    NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:date options:0];
    return newDate;
}
#pragma mark- 返回明天的date
- (NSDate*)nextDay:(NSDate *)date{
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.day = +1;
    NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:date options:0];
    return newDate;
}
#pragma mark- 获取当前时间是几号
- (NSInteger)day:(NSDate *)date{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    return [components day];
}
#pragma mark- 获取当月第一天的星期数
- (NSInteger)firstWeekdayInThisMonth:(NSDate *)date{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    [calendar setFirstWeekday:1];//1.Sun. 2.Mon. 3.Thes. 4.Wed. 5.Thur. 6.Fri. 7.Sat.
    NSDateComponents *comp = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    [comp setDay:1];
    NSDate *firstDayOfMonthDate = [calendar dateFromComponents:comp];
    
    NSUInteger firstWeekday = [calendar ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitWeekOfMonth forDate:firstDayOfMonthDate];
    return firstWeekday - 1;
}
#pragma mark- 获取当月天数
- (NSInteger)totaldaysInThisMonth:(NSDate *)date{
    NSRange totaldaysInMonth = [[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
    return totaldaysInMonth.length;
}

@end

第三步 自定义CollectionViewCell 和UICollectionReusableView

CalendarDateItem.h

#import <UIKit/UIKit.h>
@class CalendarDateModel;
@interface CalendarDateItem : UICollectionViewCell

- (void)setModel:(CalendarDateModel *)model;

@end

.m

#import "CalendarDateItem.h"
#import "CalendarDateModel.h"

#define COLOFOR0X(c)    [UIColor colorWithRed:((c>>16)&0xFF)/255.0  \
green:((c>>8)&0xFF)/255.0   \
blue:(c&0xFF)/255.0         \
alpha:1.0]
#define COLORMAINBLUE COLOFOR0X(0x00b7f3)

@interface CalendarDateItem ()
@property (weak, nonatomic) IBOutlet UILabel *dayLabel;
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;

@end

@implementation CalendarDateItem

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setModel:(CalendarDateModel *)model{
    
    _dayLabel.text = model.day;
    
    if ([_dayLabel.text isEqualToString:@""]) {
        _priceLabel.hidden = YES;
    }else{
        
        if (model.isPast) {
            _dayLabel.textColor = COLOFOR0X(0xbfbfbf);
            _priceLabel.hidden = YES;
        }else{
            _dayLabel.textColor = COLORMAINBLUE;
            _priceLabel.hidden = NO;
        }
    }
    
}
@end

image.png

CalendarMonthHeaderView.h

#import <UIKit/UIKit.h>

@interface CalendarMonthHeaderView : UICollectionReusableView

- (void)setDateString:(NSString *)date;

@end

.m

#import "CalendarMonthHeaderView.h"

@interface CalendarMonthHeaderView ()
@property (weak, nonatomic) IBOutlet UILabel *dateLabel;

@end

@implementation CalendarMonthHeaderView

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setDateString:(NSString *)date{
    
    NSArray *array = [date componentsSeparatedByString:@"-"];
    
    _dateLabel.text = [NSString stringWithFormat:@"%@ 年 %@ 月", array[0], array[1]];
}

@end

第四步 实现效果

#import "CalendarController.h"
#import "CalendarDateItem.h"
#import "CalendarMonthHeaderView.h"
#import "CalendarDateManager.h"

#define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)

@interface CalendarController ()<UICollectionViewDelegateFlowLayout, UICollectionViewDataSource>
@property (weak, nonatomic) IBOutlet UICollectionView *selectLiveTimeCollectionView;
@property (nonatomic, copy) NSArray *dateDataArray;
@end

@implementation CalendarController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UINib *nib = [UINib nibWithNibName:@"CalendarDateItem" bundle:nil];
    [_selectLiveTimeCollectionView registerNib:nib forCellWithReuseIdentifier:@"CalendarDateItem"];
    
    [_selectLiveTimeCollectionView registerNib:[UINib nibWithNibName:@"CalendarMonthHeaderView" bundle:nil]
     forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"CalendarMonthHeaderView"];
}

- (NSArray *)dateDataArray{
    
    if (!_dateDataArray) {
        _dateDataArray = [[[CalendarDateManager alloc] init] getDateArray];
    }
    return _dateDataArray;
}

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

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return 42;
    
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    CalendarDateItem *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CalendarDateItem" forIndexPath:indexPath];
    
    NSDictionary *dic = _dateDataArray[indexPath.section];
    
    NSArray *tmpArray = dic[@"itemList"];
    
    [cell setModel:tmpArray[indexPath.row]];
    
    return cell;
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    return CGSizeMake(SCREEN_WIDTH / 7.0, 45);
    
}


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

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    
    return 0;
    
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    
    if (kind == UICollectionElementKindSectionHeader) {
        
        CalendarMonthHeaderView *headerRV = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"CalendarMonthHeaderView" forIndexPath:indexPath];
        
        NSDictionary *dic = _dateDataArray[indexPath.section];
        
        [headerRV setDateString:dic[@"date"]];
        
        return headerRV;
        
    }else{
        return nil;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    return CGSizeMake(SCREEN_WIDTH, 111);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    return CGSizeMake(0, 0);
}

@end
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,569评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,499评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,271评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,087评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,474评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,670评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,911评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,636评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,397评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,607评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,093评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,418评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,074评论 3 237
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,092评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,865评论 0 196
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,726评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,627评论 2 270

推荐阅读更多精彩内容