iOS自定义日历控件

TXCalendarPicker.h


#import


@interface TXCalendarPicker : UIView


@property(nonatomic,strong) UICollectionView *collectionView;

@property (nonatomic , strong) NSDate *date;

@property (nonatomic , strong) NSDate *today;

@property (nonatomic, copy) void(^calendarBlock)(NSInteger day, NSInteger month, NSInteger year,NSString *weekDay);



@end



TXCalendarPicker.m


#import "TXCalendarPicker.h"

#import "TXCalendarCell.h"

#import "TXSportsViewController.h"



//NSString *const TXCalendarCellIdentifier = @"cell";


@interface TXCalendarPicker ()




@property (nonatomic , strong) NSArray *weekDayArray;


@property (nonatomic , strong) NSMutableDictionary *cellDic;



@property (nonatomic , strong) NSIndexPath *indexPath;


@property (nonatomic , assign) NSInteger selectedDate;


@property (nonatomic , assign) NSInteger selectedMonth;


@end



@implementation TXCalendarPicker



-(NSMutableDictionary *)cellDic {

    

    if (!_cellDic) {

        

        _cellDic = [NSMutableDictionary dictionary];

        

        

    }

    

    

    return _cellDic;

    

    

    

    

    

}




-(instancetype)initWithFrame:(CGRect)frame {

    

    self = [super initWithFrame:frame];

    

    if (self) {

        

        

        _weekDayArray = @[@"",@"",@"",@"",@"",@"",@""];

        

        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];

//        layout.scrollDirection = UICollectionViewScrollDirectionVertical;

        

        

        self.collectionView = [[UICollectionView alloc]initWithFrame:self.bounds collectionViewLayout:layout];

        

        

        self.collectionView.dataSource = self;

        self.collectionView.delegate = self;

        

        self.collectionView.showsVerticalScrollIndicator = NO;

        

        self.collectionView.showsHorizontalScrollIndicator = NO;

        

        self.collectionView.pagingEnabled = YES;

        

        self.collectionView.backgroundColor = YBGrayColor(236);

        

        

        [self addSubview:self.collectionView];

        

        

        [self addSwipe];

        

          }

    

    return self;

}



-(void)layoutSubviews {

    

    [super layoutSubviews];

    

    

    self.collectionView.x = 0;

    self.collectionView.y = 0;

    self.collectionView.size = self.size;

    

    

}











#pragma -mark collectionView delegate


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView

{

    return 2;

}



- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    

    if (section == 0) {

        return _weekDayArray.count;

    } else {

        return 42;

    }

    

}


// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    

    // 每次先从字典中根据IndexPath取出唯一标识符

    NSString *identifier = [_cellDic objectForKey:[NSString stringWithFormat:@"%@", indexPath]];

    // 如果取出的唯一标示符不存在,则初始化唯一标示符,并将其存入字典中,对应唯一标示符注册Cell

    if (identifier == nil) {

        

        identifier = [NSString stringWithFormat:@"cell%@",[NSString stringWithFormat:@"%@", indexPath]];

        [_cellDic setValue:identifier forKey:[NSString stringWithFormat:@"%@", indexPath]];

        // 注册Cell

        [self.collectionView registerClass:[TXCalendarCell class]  forCellWithReuseIdentifier:identifier];

    }

    

    TXCalendarCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

    

    

    if (indexPath.section == 0) {

        

        [cell.dateLabel setText:_weekDayArray[indexPath.row]];

        

        [cell.dateLabel setTextColor:[UIColor redColor]];

        

    }else {

        

        if (indexPath == self.indexPath) {

            

            cell.contentView.backgroundColor = [UIColor clearColor];

            

            

        }

        

        

        NSInteger daysInThisMonth = [self totaldaysInMonth:_date];

        NSInteger firstWeekday = [self firstWeekdayInThisMonth:_date];

        

        NSInteger day = 0;

        NSInteger i = indexPath.row;

        

        if (i < firstWeekday) {

            [cell.dateLabel setText:@""];

            

        }else if (i > firstWeekday + daysInThisMonth - 1){

            [cell.dateLabel setText:@""];

        }else{

            day = i - firstWeekday + 1;

            if (day == 1) {

                

                [cell.dateLabel setText:[NSString stringWithFormat:@"%zd",[self month:_date]]];

                [cell.dateLabel setTextColor:[UIColor blackColor]];

                

            }else{

                

                

                [cell.dateLabel setText:[NSString stringWithFormat:@"%zd",day]];

                [cell.dateLabel setTextColor:[UIColor blackColor]];

            }

            

            

            //this month

            if ([_today isEqualToDate:_date]) {

                

        

                if (day == [self day:_date]) {

                    

                    cell.dateLabel.text = @"今天";

                   

                    if (!self.indexPath) {

                        

                        self.indexPath = indexPath;

                        

                    }

                    

                    if (!self.selectedDate) {

                        

                        self.selectedDate = day;

                        

                    }

                    

                    if (!self.selectedMonth) {

                        

                        self.selectedMonth = [self month:_date];

                    }

                    

                    

                    

                } else if (day > [self day:_date]) {

                    

                    [cell.dateLabel setTextColor:[UIColor grayColor]];

                    

                    

                }else {

                    

                   


                    

                    

                }

            } else if ([_today compare:_date] == NSOrderedAscending) {

                

                [cell.dateLabel setTextColor:[UIColor grayColor]];

                

                


                

            }else {

                

                

                


                

                

            }

            

            

            if (day == self.selectedDate && [self month:_date] == self.selectedMonth) {

                

                [cell.dateLabel setTextColor:[UIColor whiteColor]];

                cell.contentView.layer.cornerRadius = cell.contentView.height/2;

                cell.contentView.backgroundColor = YBARGBColor(255, 245, 220, 62);

                

            }else {

                

                cell.contentView.backgroundColor = [UIColor clearColor];

                

            }

            

            

            

        }

        


    }

    return cell;

    

}


- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath

{

    return YES;

}




- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath

{

    if (indexPath.section == 1) {

        NSInteger daysInThisMonth = [self totaldaysInMonth:_date];

        NSInteger firstWeekday = [self firstWeekdayInThisMonth:_date];

        

        NSInteger day = 0;

        NSInteger i = indexPath.row;

        

        if (i >= firstWeekday && i <= firstWeekday + daysInThisMonth - 1) {

            day = i - firstWeekday + 1;

            

            //this month

            if ([_today isEqualToDate:_date]) {

                

                if (day <= [self day:_date]) {

                    

                    return YES;

                    

                }

            } else if ([_today compare:_date] == NSOrderedDescending) {

                

                return YES;

                

            }

        }

    }

    return NO;

}


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

{

    NSDateComponents *comp = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday) fromDate:self.date];

    NSInteger firstWeekday = [self firstWeekdayInThisMonth:_date];

    

    NSInteger day = 0;

    NSInteger i = indexPath.row;

    day = i - firstWeekday + 1;

    

    

    NSString *compWeekDay = [self arabicNumeralsToChinese:i];

    

    TXCalendarCell *preCell = [self.collectionView cellForItemAtIndexPath:self.indexPath];

    

    

    [preCell.dateLabel setTextColor:[UIColor blackColor]];

    preCell.contentView.backgroundColor = [UIColor clearColor];

    

    

    TXCalendarCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];

    

    [cell.dateLabel setTextColor:[UIColor whiteColor]];

    cell.contentView.layer.cornerRadius = cell.contentView.height/2;

    cell.contentView.backgroundColor = YBARGBColor(255, 245, 220, 62);

    

    self.indexPath = indexPath;

    

    if ([cell.dateLabel.text containsString:@""]) {

        

        self.selectedDate = 1;

        

    }else {

        

        

        self.selectedDate = [cell.dateLabel.text integerValue];

        

    }

    


    

    

    

    self.selectedMonth = [comp month];


    if (self.calendarBlock) {

        self.calendarBlock(day, [comp month], [comp year],compWeekDay);

        

    }

    

    

    


}



#pragma mark ---- UICollectionViewDelegateFlowLayout


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

{

    

        

        return CGSizeMake(self.width/9, self.width/9);


    

}





- (void)setDate:(NSDate *)date

{

    _date = date;

    


    [_collectionView reloadData];

    

}





-(NSString *)arabicNumeralsToChinese:(NSInteger)number


{

    

    switch (number%7) {

            

        case 0:

            

            return @"";

            

            break;

            

        case 1:

            

            return @"";

            

            break;

            

        case 2:

            

            return @"";

            

            break;

            

        case 3:

            

            return @"";

            

            break;

            

        case 4:

            

            return @"";

            

            break;

            

        case 5:

            

            return @"";

            

            break;

            

        case 6:

            

            return @"";

            

            break;

            

        default:

            

            return nil;

            

            break;

            

    }

}





- (void)addSwipe

{

    UISwipeGestureRecognizer *swipLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(nexAction:)];

    swipLeft.direction = UISwipeGestureRecognizerDirectionLeft;

    [self addGestureRecognizer:swipLeft];

    

    UISwipeGestureRecognizer *swipRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(previouseAction:)];

    swipRight.direction = UISwipeGestureRecognizerDirectionRight;

    [self addGestureRecognizer:swipRight];

}



-(void)previouseAction:(UIButton *)sender {

        

        [UIView transitionWithView:self duration:0.5 options:UIViewAnimationOptionTransitionNone animations:^(void) {

            self.date = [self lastMonth:self.date];

            


            

            

        } completion:nil];

    

    


}


-(void)nexAction:(UIButton *)sender {

    

        

        

    [UIView transitionWithView:self duration:0.5 options:UIViewAnimationOptionTransitionNone animations:^(void) {

        self.date = [self nextMonth:self.date];

        


    } completion:nil];


    

}



#pragma mark - date


- (NSInteger)day:(NSDate *)date{

    NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitDay) fromDate:date];

    return [components day];

}



- (NSInteger)month:(NSDate *)date{

    NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitMonth) fromDate:date];

    return [components month];

}


- (NSInteger)year:(NSDate *)date{

    NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear) fromDate:date];

    return [components year];

}



- (NSInteger)weekDay:(NSDate *)date{

    NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitWeekday) fromDate:date];

    return [components weekday];

}



- (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;

}


- (NSInteger)totaldaysInThisMonth:(NSDate *)date{

    NSRange totaldaysInMonth = [[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];

    return totaldaysInMonth.length;

}


- (NSInteger)totaldaysInMonth:(NSDate *)date{

    NSRange daysInLastMonth = [[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];

    return daysInLastMonth.length;

}


- (NSDate *)lastMonth:(NSDate *)date{

    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];

    dateComponents.month = -1;

    NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:date options:0];

    return newDate;

}


- (NSDate*)nextMonth:(NSDate *)date{

    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];

    dateComponents.month = +1;

    NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:date options:0];

    return newDate;

}




@end




TXCalendarCell.h



#import


@interface TXCalendarCell : UICollectionViewCell


@property (nonatomic , strong) UILabel *dateLabel;


@end




TXCalendarCell.m




#import "TXCalendarCell.h"


@implementation TXCalendarCell


- (UILabel *)dateLabel

{

    if (!_dateLabel) {

        _dateLabel = [[UILabel alloc] initWithFrame:self.bounds];

        [_dateLabel setTextAlignment:NSTextAlignmentCenter];

        [_dateLabel setFont:[UIFont systemFontOfSize:15]];


        [self addSubview:_dateLabel];

    }

    return _dateLabel;

}





@end


 

ViewController.h


-(void)settingCalendarPickerView {

    

    self.calendarPickerView = [[TXCalendarPicker alloc]init];

    

    self.calendarPickerView.backgroundColor = [UIColor orangeColor];

    

    self.calendarPickerView.size = CGSizeMake(self.view.width, 2);

    

    self.calendarPickerView.x = 0;

    self.calendarPickerView.y = 56;

    

    

    self.calendarPickerView.today = [NSDate date];

    self.calendarPickerView.date = self.calendarPickerView.today;

    self.calendarPickerView.calendarBlock = ^(NSInteger day, NSInteger month, NSInteger year,NSString *weekDay){

        

        

        if (day == [self day:[NSDate date]] && month == [self month:[NSDate date]] && year == [self year:[NSDate date]]) {

            

            self.titleLabel.text = [NSString stringWithFormat:@"今天 %@",weekDay];

            

            

        }else if (day == [self day:[NSDate date]] - 1 && month == [self month:[NSDate date]] && year == [self year:[NSDate date]]) {

            

            self.titleLabel.text = [NSString stringWithFormat:@"昨天 %@",weekDay];

            

        }else {

            

            self.titleLabel.text = [NSString stringWithFormat:@"%zd %zd %@",month,day,weekDay];

            

        }

        


        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

            

            [self hide];

            

        });

        


        

    };


    

    [self.backgroundView addSubview:self.calendarPickerView];

    

    

    

    

 

}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值