iOS collectionview的headerView的正確使用方法

問題:

  1. collectionview 的header會重復添加。
  2. 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;
}

希望有好辦法的朋友給個連接。
希望能幫助遇到過同樣問題的小伙伴吧。。

---來自濤胖子的工作筆記

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容