在UICollectionView中重载UILabel

我正在使用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; } 

任何一个帮助我?

这个单元格会使用UICollectionView的回收站出队 – 标签本身停留在回收单元格中,因此不需要重新分配,只需要find放置的位置即可:

 #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; } 

你必须为你的标签的实例生成一次。

但正如我在你的方法中看到的,每次调用方法时都会得到一个新的标签实例。

基本上,你可以UICollectionViewCell一个UICollectionViewCell ,然后只生成一次所需的标签。 在此处显示的委托方法中,只应使用所需信息更新它们。