UICollectionViewCell索引号不准确

时间:2013-12-18 17:46:45

标签: ios iphone objective-c uicollectionview uicollectionviewcell

我想在UICollectionView

中的单元格的每个偶数位置显示一个问号 我是这样写的:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
     UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
if (indexPath.row %2 ==0){
                UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(50, 50, 20, 20)];
                [image setImage:[UIImage imageNamed:@"missing"]];
                [cell.contentView addSubview:image];
          }

        return cell;

}

我第一次看到UICollectionView - 图像正在显示属性 - 在每个偶数上:0,2,4但是当我开始水平向右和向左滚动时,几乎每个单元格都会添加图片而不管我条件:indexPath.row %2 ==0

我该如何预防呢?如何确保即使在滚动期间索引路径也不会更改?

我正在为ios7写作

2 个答案:

答案 0 :(得分:1)

这种情况正在发生,因为您的旧单元格正在重复使用,并且您不会重置它们的外观。在else中的if条件中添加collectionView:cellForItemAtIndexPath:数据块,然后在那里清理您的信箱,例如通过从单元格中删除图像视图,或类似的东西。

你想要的是这样的:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
     UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
    if (indexPath.row %2 ==0){
        UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(50, 50, 20, 20)];
        [image setImage:[UIImage imageNamed:@"missing"]];
        [cell.contentView addSubview:image];
    }
    else { 
        // Code to clean up the cell goes here.
    }

    return cell;
}

答案 1 :(得分:0)

  • (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {  UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@“Cell”forIndexPath:indexPath];

    UIImageView * image = [[UIImageView alloc] initWithFrame:CGRectMake(50,50,20,20)];

    if(indexPath.row%2 == 0){

    [image setImage:[UIImage imageNamed:@"missing"]];
    [cell.contentView addSubview:image];
    

    } 其他 {

    [image setImage:[UIImage imageNamed:@""]];
    [cell.contentView addSubview:image];
    

    }

    返回细胞; }