ios - 自定义 UICollectionViewCell 中的 UIImageView 始终返回 nil

标签 ios objective-c uicollectionviewcell

好的,在我的 Storyboard中,我制作了一个包含 3 个单元格的 UICollectionView。我为其中一个单元格创建了一个自定义类,它显然扩展了 UICollectionViewCell:

enter image description here

然后我在我的 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/

相关文章:

ios - UIButton 在 IOS 6 中显示默认的带圆角的白色背景,但在 IOS 7 中没有

ios - UILocalNotification 多次触发 swift

ios - ObjC 如何在选择 TabBarItem 时弹出回 RootViewController

ios - NSURLConnection 在另一个线程中启动。未调用委托(delegate)方法

ios - UICollectionViewCell 中的 UILabel 有时大小不正确

ios - 如何在社交媒体帖子中显示 UIView

ios - 当父容器 View 约束以编程方式更改时,UINavigationController subview 不调整大小

objective-c - 调整 Mac 显示器亮度 Objective-C?

ios - 将 subview 添加到 UICollectionViewCell 一次(单元格可用性问题)

swift - 如何在单元格之间获得更均匀的垂直距离?