ios中自定义tableView,CollectionView的cell什么时候用nib加载,什么时候用标识重用

做了一段时间的iOS,在菜鸟的路上还有很长的路要走,把遇到的问题记下来,好记性不如烂笔头。

在项目开发中大家经常会用到tableView和collectionView两个控件,然而在cell的自定义上会有一定的不同

tableView

1.纯代码自定义cell,直接用init方法自定义,然后在UITableViewCell* 里面自己根据标识加载

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{

    self =[super initWithStyle:style reuseIdentifier:reuseIdentifier];

    if (self) {

        [self initSubview];

    }

    return  self;

}

-(void)initSubview{

    _monthLabel = [[UILabel alloc]init];

    [self.contentView addSubview:_monthLabel];

    

    _moneyLabel=[[UILabel alloc]init];

    [self.contentView addSubview:_moneyLabel];

    

    _sepLineView = [[UIView alloc]init];

    [self.contentView addSubview:_sepLineView];

}

 

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString*cellID = @"ProperTableViewCell";

    ProperTableViewCell*cell = [tableView dequeueReusableCellWithIdentifier:cellID];

    if (cell==nil) {

        cell = [[ProperTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];

    }

 

2.用了xib拖线自定义cell

xib拖线自定义需要注意点:在vc中加载时需要注册

 [_tableView registerNib:[UINib nibWithNibName:[ ProperTableViewCell class] bundle:nil] forCellReuseIdentifier:@"ProperTableViewCell"];

 

或者

//注册headerView Nibview需要继承UICollectionReusableView

    [self.collectionView registerNib:[UINib nibWithNibName:@"ProductItemCell" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"ProductItemCell"];

然后根据标识找到对应的cell

 

 

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString*cellID = @"ProperTableViewCell";

    ProperTableViewCell*cell = [tableView dequeueReusableCellWithIdentifier:cellID];

    if (cell==nil) {

        cell = [[ProperTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];

    }

 

 

3.如果cell是用xib自定义的,在cell的加载那里注册之后,可以用nib的方法来加载

 static NSString * CellIdentifier = @"ProductItemCell";

    

    if(!nibri)

    {

        UINib *nib = [UINib nibWithNibName:@"ProductItemCell" bundle:nil];

        [self.collectionView registerNib:nib forCellWithReuseIdentifier:CellIdentifier];

        nibri =YES;

    }

    ProductItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];

4.注意collectionView和tableView的混合使用

collectionView和tableview 的混合使用时,需要数据实时刷新,如果重用数据的话需要用nib方式加载,不然会出现数据错乱情况

 用下面这种方法来创建cell

 // 重用数据会用的是缓存池的数据没有刷新,但是tableviewcell每次滚动时数据会重用,所以不能用标识重用

    NSArray *nib =[[NSBundle mainBundle]loadNibNamed:@"hangyeCell" owner:nil options:nil];

    hangyeCell *cell = [nib objectAtIndex:0];

 

 

 

posted @ 2016-12-06 11:02  雅尘恋  阅读(746)  评论(0编辑  收藏  举报