ios UICollectionView cells not refreshing after scroll

一世执手 提交于 2019-12-11 19:54:04

问题


I have a basic UICollectionView that if I scroll will "redraw" the label on top of the cells,

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{


    UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];


    cell.backgroundColor=[UIColor greenColor];

    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, cell.bounds.size.width, 40)];
    [cell.contentView addSubview:title];

    //NSString *titleLbl = [NSString stringWithFormat:@"i = %d", indexPath.row];


    title.text = [self.arraya objectAtIndex:indexPath.row];

    return cell;
}

How to fix it so it refreshes the proper cell after scrolling? Cheers


回答1:


When you do this:

UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, cell.bounds.size.width, 40)];
[cell.contentView addSubview:title];

You're creating a new title every time and adding it to your contentView. Instead, try adding a tag to your UILabel and changing your existing UILabel's text, like so:

UILabel *title = (UILabel *)[cell.contentView viewWithTag:SOME_NUMBER];
if (!title) {
    title = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, cell.bounds.size.width, 40)];
    title.tag = SOME_NUMBER;
    [cell.contentView addSubview:title];
}
title.text = @"your new text"


来源:https://stackoverflow.com/questions/22137536/ios-uicollectionview-cells-not-refreshing-after-scroll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!