UICollectionView 中的 UILabel 重载
Posted
技术标签:
【中文标题】UICollectionView 中的 UILabel 重载【英文标题】:UILabel overloading in UICollectionView 【发布时间】:2014-02-13 12:02:02 【问题描述】:我正在使用UICollectionView
。每次我使用此代码时,集合视图中的标签都会超载
- (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;
有人帮帮我吗?
【问题讨论】:
哪个有超载的意思? cellForItemAtIndexPath 每次滚动时都会调用 @dolo 重载意味着每次滚动集合视图时都会加载标签,并且它会在单个图像上显示多个标签。 @iDev 是的,每次都会调用 【参考方案1】:单元格将使用 UICollectionView 的回收器出列 - 标签本身保留在回收的单元格中,因此无需重新分配它,您只需要找到放置它的位置即可:
#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;
【讨论】:
感谢您提供简单的解决方案。【参考方案2】:在单元格的生命周期内,您只需生成一次标签实例。
但是正如我在您的方法中看到的,每次调用该方法时,您都会获得一个新的标签实例。
基本上,您可以将UICollectionViewCell
子类化,然后只生成一次所需的标签。在此处显示的委托方法中,您应该只使用所需信息更新它们。
【讨论】:
以上是关于UICollectionView 中的 UILabel 重载的主要内容,如果未能解决你的问题,请参考以下文章
UICollectionView 中的 UILabel 重载