好的,在我的 Storyboard中,我制作了一个包含 3 个单元格的 UICollectionView。我为其中一个单元格创建了一个自定义类,它显然扩展了 UICollectionViewCell:
然后我在我的 ViewDiDApear 中注册了类(class):
[self.collectionView registerClass:[DeviceImageCell class] forCellWithReuseIdentifier:@"Cell1"];
我还为该特定单元格添加了一个 imageView,并在我的自定义类中为该 imageView 添加了一个导出。当我制作我的自定义单元格时出现问题,它忘记了我 Storyboard中设置的所有内容,也就是背景颜色,我的 ImageView 所在的位置等等。因此,我的 imageView 一直返回 nil。
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.row == 0)
{
static NSString *identifier = @"Cell1";
DeviceImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
UIImage *image = [UIImage imageNamed:@"dysart-woods-full.jpg"];
cell.imageview.image = image;
cell.backgroundColor = [UIColor blueColor];
//cell.imageview.image = image;
return cell;
}
else if(indexPath.row == 1)
{
static NSString *identifier = @"Cell2";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
return cell;
}
else
{
static NSString *identifier = @"Cell3";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
UIImageView *imageView = (UIImageView *)[cell viewWithTag:1];
imageView.image = [UIImage imageNamed:@"dysart-woods-full.jpg"];
return cell;
}
}
最佳答案
你可能早就解决了这个问题。
然而对于那些发现这个并且有同样问题的人
它是 viewDidAppear
中的 registerClass
调用
[self.collectionView registerClass:[DeviceImageCell class] forCellWithReuseIdentifier:@"Cell1"];
您已经在 Interface Builder 中注册了该类,因此调用 registerClass:forCellWithReuseIdentifier:
正在替换 IB 创建的条目。
删除此行将解决问题。
关于ios - 自定义 UICollectionViewCell 中的 UIImageView 始终返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19523507/