uicollectionview,UICollectionView的特定indexPath.row中的单元格无法设置标题

时间:2012-11-22 21:36:03

标签: objective-c ios uicollectionview uicollectionviewcell

在处理UICollectionView时,我正在从nib加载一个单元格,如下所示

- (void)viewDidLoad
{
    [super viewDidLoad];
    /* Uncomment this block to use nib-based cells */
    UINib *cellNib = [UINib nibWithNibName:@"NibCell" bundle:nil];
    [self.collectionView registerNib:cellNib forCellWithReuseIdentifier:@"cvCell"];


    // Configure layout
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.collectionView.contentInset    =   UIEdgeInsetsMake(10.0f, 0.0f, 10.0f, 0.0f);

    [flowLayout setItemSize:CGSizeMake(300, 200)];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    [self.collectionView setCollectionViewLayout:flowLayout];
}

我的nib文件如下所示

enter image description here

顶部标签用于显示单元格数量,中间标签用于显示特定文本

在方法 cellForItemAtIndexPath 中,我只想将文本设置为某行的单元格(在本例中,我在1行进行):

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

     // Setup cell identifier
     static NSString *cellIdentifier = @"cvCell";

     UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
     UILabel *titleLabel    = (UILabel *)[cell viewWithTag:100];
     UILabel *cellLablel    = (UILabel *)[cell viewWithTag:200];
     cellLablel.text         =   self.dataArray[0][indexPath.row];
     if ( indexPath.row == 1)
         [titleLabel setText:@"this is row 1"];

    return cell;

}

运行应用时,会出现问题。 row1 的单元格不仅 titleLabel 设置为This is row 1,但也设置了row5的titleLabel和row9以及row10: enter image description here

enter image description here

如果有人知道我在中间做错了什么。请帮忙。

我的收藏品包含1节和15节。

1 个答案:

答案 0 :(得分:3)

细胞被重复使用。只要向下滚动并且单元格1不可见,集合视图就会再次使其可用。只需为所有单元格设置文本,例如

titleLabel.text = [NSString stringWithFormat:@"this is row %d", indexPath.row];