今天封装了个日历,分享出来和大家一起探讨。
我先拿个效果图来看看
大体思路 首先确定每个月第一天是星期几,这样就知道了怎么样排列,也可以根据当月天数计算出有多少个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。资源我已上传,需要的可以去下载
这是我为自己封装多个项目通用的,有不足的地方请大神指点。大家也可以一起讨论