UILabel overloading in UICollectionView

2019-03-01 16:50发布

I am using UICollectionView. in collection view label is overload every time i am using this code

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

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

     UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5.0, 90.0,90.0, 21.0)];

    [label setTag : indexPath.row];

    label.text = [NSString stringWithFormat:@"%@",[arrImages objectAtIndex:indexPath.row]];

    label.textColor = [UIColor redColor];

    label.backgroundColor = [UIColor clearColor];

    label.font = [UIFont boldSystemFontOfSize:12];

    label.textColor = [UIColor colorWithRed:46.0/255.0 green:63.0/255.0 blue:81.0/255.0 alpha:1.0];

    [cell.contentView addSubview:label];

return cell;
}

any one help me ?

2条回答
聊天终结者
2楼-- · 2019-03-01 17:26

You have to generate the instance of your label just once, for the life - time of the cell.

But as I see in your method, you will get a new instance of the label every time the method is called.

Basically, you can subclass a UICollectionViewCell and then generate the required label only once. In the delegate method shown here, you should only update them with required information.

查看更多
劳资没心,怎么记你
3楼-- · 2019-03-01 17:35

The cell will get dequeued using UICollectionView's recycler - the label itself stays at the recycled cell, so there's no need in re-allocating it, you just need to find where you placed it:

#define LABEL_TAG 100001

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

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

    UILabel *label = (UILabel*)[cell.contentView viewWithTag:LABEL_TAG];

    if (!label) {
        label = [[UILabel alloc] initWithFrame:CGRectMake(5.0, 90.0,90.0, 21.0)];
        label.textColor = [UIColor redColor];
        label.backgroundColor = [UIColor clearColor];
        label.font = [UIFont boldSystemFontOfSize:12];
        label.textColor = [UIColor colorWithRed:46.0/255.0 green:63.0/255.0 blue:81.0/255.0 alpha:1.0];
        label.tag = LABEL_TAG;
        [cell.contentView addSubview:label];
    }

    label.text = [NSString stringWithFormat:@"%@",[arrImages objectAtIndex:indexPath.row]];
    return cell;
}
查看更多
登录 后发表回答