UICollectionView简单实现日历



  今天封装了个日历,分享出来和大家一起探讨。

我先拿个效果图来看看

大体思路 首先确定每个月第一天是星期几,这样就知道了怎么样排列,也可以根据当月天数计算出有多少个Section
我每次计算都会把时间重置为当月第一天,这样方便计算,这样可以根据Section和Row来计算日历所在时间,改变<pre name="code" class="objc">NSDateComponents 对象的 day就可以得到对应天数的<pre name="code" class="objc">NSDateComponents。需要计算的的就是在当页面板中,上个月与下个月的时间,我都是先计算出每个月的第一天的<pre name="code" class="objc">DateComponents然后在加上所在的天数。
</pre><p></p><pre>
 
 
在这里返回一个NSDateComponents对象,
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath comp:(NSDateComponents *)comp{

    UINib *nib = [UINib nibWithNibName:@"ATCalendarCollectionViewCell"
                                bundle: [NSBundle mainBundle]];
    [collectionView registerNib:nib forCellWithReuseIdentifier:@"Calendarcell"];
    ATCalendarCollectionViewCell *cell = [[ATCalendarCollectionViewCell alloc]init];
    cell  = [collectionView dequeueReusableCellWithReuseIdentifier:@"Calendarcell" forIndexPath:indexPath];

    cell.dayLab.text = [NSString stringWithFormat:@"%ld",[comp day]];
    
    return cell;
}
下面直接上代码<pre name="code" class="objc">   _calendarView = [[[NSBundle mainBundle] loadNibNamed:@"CalendarView" owner:nil options:nil]lastObject];
    _calendarView.frame = CGRectMake(15, 130, SCREEN_WIDTH -30, self.view.bounds.size.height - 130 -60);
    _calendarView.delegate = self;
    _calendarView.dataSource = self;
    [_calendarView.collectionView registerClass:[ATCalendarCollectionViewCell class] forCellWithReuseIdentifier:@"Calendarcell"];
    [self.view addSubview:_calendarView];

 
</pre><pre name="code" class="objc">



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

    UINib *nib = [UINib nibWithNibName:@"ATCalendarCollectionViewCell"
                                bundle: [NSBundle mainBundle]];
    [collectionView registerNib:nib forCellWithReuseIdentifier:@"Calendarcell"];
    ATCalendarCollectionViewCell *cell = [[ATCalendarCollectionViewCell alloc]init];
    cell  = [collectionView dequeueReusableCellWithReuseIdentifier:@"Calendarcell" forIndexPath:indexPath];

    cell.dayLab.text = [NSString stringWithFormat:@"%ld",[comp day]];
    
    return cell;
}

这里的cell自定义Cell。资源我已上传,需要的可以去下载

这是我为自己封装多个项目通用的,有不足的地方请大神指点。大家也可以一起讨论


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值