問題:
- collectionview 的header會重復添加。
- collectionview 的header數據錯亂。
tableView的header倒是沒有什么問題,但是今天在使用collectionview設置header的時候就出現問題了。
剛開始我用的系統的UICollectionReusableView 那么就會出現一個問題,在header 的地方你每次刷新他都會初始化一個 view ,打開界面一看我擦,好多個headerView 重疊在一起了,于是查了大佬們的方法,看到都是說判斷這個view 的subviews.count 如果為0那么就添加你要添加的子視圖。對這樣是解決了重疊的問題。
但是問題又來了,當你刷新的時候,你會發現你的headerView上面的數據錯亂了,此時就應該是headerView 的復用的問題了。復用了之后直接將子視圖也復用了,所以導致數據沒有根據自己的indexPath.section 去賦值。整了半天沒有明白怎么回事,然后就自定義了一個header,完美搞定。
代碼:
// headerView 的.m 文件。這個沒有說的 .h 就一個屬性
#import "CarcorderHeaderView.h"
@implementation CarcorderHeaderView
- (id)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self){
self.backgroundColor = [[UIColor alloc] initWithRed:1 green:1 blue:1 alpha:0.95];
[self createLab];
}
return self;
}
- (void)createLab{
self.headerLab = [TaoUI createLableWithText:nil backgroundColor:nil textColor:UIColorFromRGB(0x666666) font:16.0 numberOfLines:0 textAlignment:NSTextAlignmentLeft boderColor:nil];
[self addSubview:self.headerLab];
[self.headerLab mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.mas_left).offset(15);
make.right.top.bottom.equalTo(self);
}];
}
@end
collectionview 注冊headerView
[self.collectionView registerClass:[CarcorderHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerV"];
接下來在collectionview 的代理方法中操作headerView;
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
CarcorderHeaderView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerV" forIndexPath:indexPath];
// if (self.dataArr.count == 0) return view; 這里之前沒有注意,直接return view 的話 刷新會看到這個view,通過下面處理就行了。
if (self.dataArr.count == 0){
view.backgroundColor = [UIColor clearColor];
return view;
}
// 這里就隨便你怎么寫了。我這個很簡單只是一個日期的展示。。OK ,headerView 重復添加的問題搞定,數據錯亂的問題搞定。
NSString *timeStr = ((YourModel*)self.dataArr[indexPath.section][indexPath.row]).startTime
view.headerLab.text = timeStr;
}
希望有好辦法的朋友給個連接。
希望能幫助遇到過同樣問題的小伙伴吧。。
---來自濤胖子的工作筆記