iOS 封装一个简单的日历

先看下效果图:


rili.jpg

一个简单的自定义日历需求,一周从日开始,上个月的日期为灰色,点击cell选中日期并返回结果。ok!下面上菜~

1.我们先封装一个日期的类YBKDateItem,包括当前日期,具体是所属月的哪号,在UICollectionView中显示是否是属于当前月

@interface YBKDateItem : NSObject
@property (nonatomic, copy) NSString *dateString;
@property (nonatomic, assign) NSInteger day; //几号
@property (nonatomic, assign) BOOL isCurrentMonth;
+ (YBKDateItem *)dateItemWithDateString:(NSString *)dateString Day:(NSInteger)day IsCurrentMonth:(BOOL)isCurrentMonth;
@end
#import "YBKDateItem.h"

@implementation YBKDateItem
+ (YBKDateItem *)dateItemWithDateString:(NSString *)dateString Day:(NSInteger)day IsCurrentMonth:(BOOL)isCurrentMonth {
    YBKDateItem *item = [[YBKDateItem alloc] init];
    item.dateString = dateString;
    item.day = day;
    item.isCurrentMonth = isCurrentMonth;
    return item;
}
@end
  1. 再来自定义UICollectionViewCell,包括一个显示日期的label,是否是默认日期
#import <UIKit/UIKit.h>
@class YBKDateItem;
@interface YBKDatePickerCell : UICollectionViewCell
@property (nonatomic, strong) UILabel *textLabel;

- (void)setCellWithDateItem:(YBKDateItem *)item;

@property (nonatomic, assign) BOOL isDefault; //是否是默认日期
@end
#import "YBKDatePickerCell.h"
#import "YBKDateItem.h"
@interface YBKDatePickerCell ()
@property (nonatomic, strong) YBKDateItem *item;
@end

@implementation YBKDatePickerCell
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.textLabel = [UILabel new];
        self.textLabel.text = @"33";
        self.textLabel.textAlignment = 1;
        self.textLabel.textColor = RGBA(212, 212, 212, 212);
        self.textLabel.layer.cornerRadius = self.contentView.bounds.size.height / 2;
        self.textLabel.layer.masksToBounds = YES;
        [self addSubview:self.textLabel];
        [self.textLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self.contentView);
            make.width.height.mas_equalTo(self.contentView.mas_height);
        }];
    }
    return self;
}

- (void)setSelected:(BOOL)selected {
    
    [super setSelected:selected];
    if (selected) {
        self.textLabel.backgroundColor = kColor_Blue;
        self.textLabel.textColor = [UIColor whiteColor];
    } else {
        if (self.isDefault) {
            self.textLabel.backgroundColor = [UIColor orangeColor];
            self.textLabel.textColor = [UIColor whiteColor];
        } else {
            self.textLabel.backgroundColor = [UIColor whiteColor];
            if (self.item.isCurrentMonth) {
                self.textLabel.textColor = [UIColor blackColor];
            } else {
                self.textLabel.textColor = RGBA(212, 212, 212, 212);
            }
        }
    }
}
- (void)setIsDefault:(BOOL)isDefault {
    if (isDefault) {
        self.textLabel.backgroundColor = [UIColor orangeColor];
        self.textLabel.textColor = [UIColor whiteColor];
    } else {
        self.textLabel.backgroundColor = [UIColor whiteColor];
        if (self.item.isCurrentMonth) {
            self.textLabel.textColor = [UIColor blackColor];
        } else {
            self.textLabel.textColor = RGBA(212, 212, 212, 212);
        }
    }
}
- (void)setCellWithDateItem:(YBKDateItem *)item {
    self.textLabel.text = [NSString stringWithFormat:@"%ld", item.day];
    self.item = item;
    if (item.isCurrentMonth) {
        self.textLabel.textColor = [UIColor blackColor];
    } else {
         self.textLabel.textColor = RGBA(212, 212, 212, 212);
    }
}

3.下面是关于日历选择view的封装,先看看YBKDatePickerView.h中的代码

@interface YBKDatePickerView : UIView
- (instancetype)initWithFrame:(CGRect)frame WithDefaultDateString:(NSString *)defaultDateStr;
@property (nonatomic,  copy) void(^YBKDatePickerBlock)(NSString *selectDate);
@end

再瞅瞅正餐

#define kHeight_Cell    30
@interface YBKDatePickerView () <UICollectionViewDelegate, UICollectionViewDataSource, UIGestureRecognizerDelegate>
@property (nonatomic, strong) UILabel  *dateLabel;
@property (nonatomic, strong) UIButton  *preBtn;
@property (nonatomic, strong) UIButton  *nextBtn;

@property (nonatomic, strong) UICollectionView *collectionView;
//dataArr数据有5*7 或者6*7个(包括本月日期个数和上月尾下月初)
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) NSArray *weekArr; //用于一周七天创建周天
@property (nonatomic, assign) NSInteger weeksInMonths; //每个月有几周
@property (nonatomic, assign) NSInteger firstDayIndex; //每个月第一天是周几
@property (nonatomic, strong) NSCalendar *calendar;
@property (nonatomic, copy) NSString *defaultDateString;    //默认日期
@end

UI创建放到最后面,先看看最重要的日期计算

- (void)getDateData {
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];//设置时区
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeZone:timeZone];
    [dateFormatter setDateFormat:@"yyyy年MM月"];
    //先判断当前label是否有日期,没有的话,就显示获取默认日期
    if (self.dateLabel.text == nil) {
        self.dateLabel.text = [dateFormatter stringFromDate:[NSDate date]];
    }
    NSDate *date = [dateFormatter dateFromString:self.dateLabel.text];
    NSInteger interval = [timeZone secondsFromGMTForDate: date];
    date = [date dateByAddingTimeInterval:interval];
    
    //计算日期items
    NSDateComponents *components = [self.calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond|NSCalendarUnitWeekday fromDate:date];
    //获取该月有几周
    self.weeksInMonths = [self.calendar rangeOfUnit:NSCalendarUnitWeekOfMonth inUnit:NSCalendarUnitMonth forDate:date].length;
    //获取每个月第一天是周几,或当前默认日期是周几
    self.firstDayIndex = [self.calendar ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitWeekOfMonth forDate:date];

    NSDate *tmpDate =[self.calendar dateFromComponents:components];
    //日期格式化
    NSDateFormatter *dayDateFormatter = [[NSDateFormatter alloc] init];
    [dayDateFormatter setDateFormat:@"yyyy-MM-dd"];

    //初始化一个临时的数组,用于存放计算的日期
    NSMutableArray *tmpArr = [NSMutableArray arrayWithCapacity:42];
    //计算上个月剩余的天数
    for (int i = 1; i < self.firstDayIndex; i++) {
        NSDate *preDate = [NSDate dateWithTimeInterval:-24*60*60 * (self.firstDayIndex - i) sinceDate:tmpDate];
        
        NSDateComponents *daycoms = [self.calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond|NSCalendarUnitWeekday fromDate:preDate];
        YBKDateItem *item = [YBKDateItem dateItemWithDateString:[dayDateFormatter stringFromDate:preDate] Day:daycoms.day IsCurrentMonth:NO];
        [tmpArr addObject:item];
    }
    //计算本月天数
    NSInteger allDays = [self.calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date].length;
    for (int i = 1; i <= allDays; i++) {
        NSDateComponents *daycoms = [self.calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond|NSCalendarUnitWeekday fromDate:tmpDate];
        daycoms.day = i;
        NSDate *curDate = [self.calendar dateFromComponents:daycoms];
        YBKDateItem *item = [YBKDateItem dateItemWithDateString:[dayDateFormatter stringFromDate:curDate] Day:daycoms.day IsCurrentMonth:YES];
        [tmpArr addObject:item];
    }
    //计算下个月露出来的天数
    NSString *lastDateString = ((YBKDateItem *)[tmpArr lastObject]).dateString;
    
    NSDate *lastDate = [dayDateFormatter dateFromString:lastDateString];
    NSInteger lastInterval = [timeZone secondsFromGMTForDate:lastDate];
    lastDate = [lastDate dateByAddingTimeInterval:lastInterval];
    
    NSInteger count = (self.weeksInMonths * 7 -tmpArr.count);
    for (int i = 1; i <= count; i++) {
        NSDate *nextDate = [NSDate dateWithTimeInterval:24*60*60 * i sinceDate:lastDate];
        NSDateComponents *daycoms = [self.calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond|NSCalendarUnitWeekday fromDate:nextDate];
        YBKDateItem *item = [YBKDateItem dateItemWithDateString:[dayDateFormatter stringFromDate:nextDate] Day:daycoms.day IsCurrentMonth:NO];
                [tmpArr addObject:item];
    }
    //计算over,刷新collectionview
    self.dataArr = tmpArr;
    [self.collectionView reloadData];
}

然后就是点击上个月,下个月的按钮后的数据处理

- (void)getNextMonthDateForType:(BOOL)isNextMonth {
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];//设置时区
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeZone:timeZone];
    [dateFormatter setDateFormat:@"yyyy年M月"];
    NSDate *date = [dateFormatter dateFromString:self.dateLabel.text];
    NSInteger interval = [timeZone secondsFromGMTForDate: date];
    date = [date dateByAddingTimeInterval:interval];
    NSLog(@"日期:%@", date);
    
    //每个月有几周
    self.weeksInMonths = [self.calendar rangeOfUnit:NSCalendarUnitWeekOfMonth inUnit:NSCalendarUnitMonth forDate:date].length;
    //每个月第一天是周几
    self.firstDayIndex = [self.calendar ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitWeekOfMonth forDate:date];
    
    NSDateComponents *components = [self.calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond|NSCalendarUnitWeekday fromDate:date];
    //计算下一个月是几月份
    if (isNextMonth) {
        //下个月
        components.month += 1;
        if (components.month > 12) {
            components.year += 1;
            components.month -= 12;
        }
    } else {
        components.month -= 1;
        if (components.month <= 0) {
            components.year -= 1;
            components.month += 12;
        }
    }
    self.dateLabel.text = [NSString stringWithFormat:@"%ld年%ld月", components.year, components.month];
    [self getDateData];
}

再后面就是UI布局了,篇幅原因懒得贴代码了,自行想象吧~~

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    YBKDatePickerCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"YBKDatePickerCellReuse" forIndexPath:indexPath];
    YBKDateItem *item = self.dataArr[indexPath.row];
    [cell setCellWithDateItem:item];
    if ([self.defaultDateString isEqualToString:item.dateString]) {
        cell.isDefault = YES;
    } else {
        cell.isDefault = NO;
    }
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    YBKDatePickerCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"YBKDatePickerCellReuse" forIndexPath:indexPath];
    YBKDateItem *item = self.dataArr[indexPath.row];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (self.YBKDatePickerBlock) {
            self.YBKDatePickerBlock(item.dateString);
            [self removeFromSuperview];
        }
    });
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,482评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,377评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,762评论 0 342
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,273评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,289评论 5 373
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,046评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,351评论 3 400
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,988评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,476评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,948评论 2 324
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,064评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,712评论 4 323
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,261评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,264评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,486评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,511评论 2 354
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,802评论 2 345