iOS 封装一个简单的日历

先看下效果图:


iOS 封装一个简单的日历_第1张图片
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 
@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 () 
@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];
        }
    });
}

你可能感兴趣的:(iOS 封装一个简单的日历)