iOS归纳

iOS collectionview的headerView的正确

2018-05-08  本文已影响0人  追梦小怪兽

问题:

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

希望有好办法的朋友给个连接。
希望能帮助遇到过同样问题的小伙伴吧。。

---来自涛胖子的工作笔记

上一篇下一篇

猜你喜欢

热点阅读