OGeek|极客世界-中国程序员成长平台

标题: ios - ViewWithTag 导致 UICollectionView 出现问题 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 04:36
标题: ios - ViewWithTag 导致 UICollectionView 出现问题

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)collectionViewUICollectionView *)collectionView numberOfItemsInSectionNSInteger)section{
    return gridImages.count;
}


- (UICollectionViewCell *)collectionViewUICollectionView *)collectionView cellForItemAtIndexPathNSIndexPath *)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,它可以工作,但 Collection View 只是一个框,而不是 test.jpg 图像。 viewwithtag 到底是什么?

崩溃:

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

知道发生了什么吗?

编辑:抱歉,标签 100 是与我在 Storyboard 中的 collectionview 的 UIImageView 关联的标签。不过还是崩溃了



Best Answer-推荐答案


我猜你在 UICollectionViewCell 本身上设置了 100 标签,而不是在其中的 UIImageView 上。或者两个 View 具有相同的标签集。 viewWithTag 将返回它找到的带有该标签的第一个 View ,因此您希望使它们独一无二。您是否可能先不小心在整个单元格上设置了标签,然后又在 ImageView 上设置它而忘记将其从单元格中删除?任何 UIView 子类都可以有标签,所以在设置标签之前需要注意选择了哪个 View 。

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

关于ios - ViewWithTag 导致 UICollectionView 出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19330867/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4