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,它可以工作,但 Collection View 只是一个框,而不是 test.jpg 图像。 viewwithtag 到底是什么?
崩溃:
[UICollectionViewCell setImage:]: unrecognized selector sent to instance 0x1659b300'
知道发生了什么吗?
编辑:抱歉,标签 100 是与 Storyboard 中 CollectionView 的 UIImageView 关联的标签。但仍然崩溃
最佳答案
我不得不猜测您在 UICollectionViewCell 本身上设置了 100 标签,而不是在其中的 UIImageView 上。或者两个 View 具有相同的标签集。 viewWithTag 将返回它找到的带有该标签的第一个 View ,因此您希望使它们唯一。您是否可能先不小心将标签设置在整个单元格上,然后将其设置在 ImageView 上,而忘记将其从单元格中删除?任何 UIView 子类都可以有标签,因此在设置标签之前需要小心选择哪个 View 。
崩溃是因为 viewWithTag: 方法返回 UICollectionViewCell 实例,并且它没有实现您在其上调用的 setImage: 方法(通过“gridImageView.image = ...”行)。
关于ios - ViewWithTag 导致 UICollectionView 出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19330867/