ViewWithTag导致UICollectionView出现问题

时间:2013-10-12 05:25:06

标签: ios objective-c uicollectionview uicollectionviewcell

I followed this tutorial to create a UICollectionView.我复制了他们的代码没有问题,但是当我尝试它时,它崩溃了

- (void)viewDidLoad
{
    [super viewDidLoad];
    gridImages = [[NSMutableArray alloc]init];
    [gridImages addObject: @"test.jpg"];
    [gridImages addObject: @"test.jpg"];
    [gridImages addObject: @"test.jpg"];
    [gridImages addObject: @"test.jpg"];
    [gridImages addObject: @"test.jpg"];

}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return gridImages.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"Cell";

    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

    UIImageView *gridImageView = (UIImageView *)[cell viewWithTag:100];

    gridImageView.image = [UIImage imageNamed:[gridImages objectAtIndex:indexPath.row]];

    return cell;
}

崩溃发生在这一行:

 UIImageView *gridImageView = (UIImageView *)[cell viewWithTag:100];

如果我将viewwithtag更改为99或101,它可以工作,但集合视图只是一个框,而不是test.jpg图像。 viewwithtag究竟是什么?

碰撞:

[UICollectionViewCell setImage:]: unrecognized selector sent to instance 0x1659b300'

知道发生了什么事吗?

编辑:对不起,标签100是与故事板中集合视图的UIImageView关联的标签。仍然崩溃

2 个答案:

答案 0 :(得分:4)

我不得不猜测你在UICollectionViewCell本身设置了100个标签,而不是它里面的UIImageView。或者两个视图具有相同的标记集。 viewWithTag将返回它使用该标记找到的第一个视图,因此您希望使它们唯一。您是否可能首先在整个单元格上设置标记,然后在忘记将其从单元格中删除的同时将其设置在图像视图上?任何UIView子类都可以有一个标记,因此在设置标记之前需要注意选择哪个视图。

崩溃是因为viewWithTag:方法正在返回一个UICollectionViewCell实例,并且它没有实现你在它上面调用的setImage:方法(通过“gridImageView.image = ...”行)。

答案 1 :(得分:0)

要添加到接受的答案,方法viewWithTag:首先搜索接收者,然后搜索其所有子视图以比较标记。因此,如果接收器指定了标签,则将返回该标签。 从异常中可以清楚地看到,{I}在IICollectionViewCell而不是UIImageView上调用了setImage:方法

相关问题