ios - 从 UICollectionViewCell 实例访问图像时遇到问题

标签 ios uicollectionview uicollectionviewcell

我正在按照本教程对我的项目进行一些修改:http://www.appcoda.com/ios-programming-uicollectionview-tutorial/

我正在尝试获取 IB 为我创建的 UIImageView 实例。

这是我的 IB 的屏幕截图:

enter image description here

我有一个名为 FeedViewCell 的自定义类,它包含一个 UIImageView。这是 cellForItemAtIndexPath 代码:

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

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

    UIImageView *imageView = (UIImageView *)[cell viewWithTag:100];
    imageView.image = [UIImage imageNamed:[postPhotos objectAtIndex:indexPath.row]];

    return cell;
}

问题是 UIImageView *imageView = (UIImageView *)[cell viewWithTag:100];返回为零。无论如何,使用 viewWIthTag 方法对我来说似乎很奇怪,但在调试器中我没有看到 imageView 是 UICollectionViewCell subview 的迹象。如果您查看此调试屏幕,您可以看到该单元格似乎没有任何 UIImageView subview :

enter image description here

但是我看到 2 个 UIImageView 作为 CollectionView 的 subview 。

所以看来我在IB中做错了什么。这并不奇怪,因为我似乎总是与 IB 作斗争(查看代码至少我可以看到发生了什么)。

感谢您的建议!

更新:我放弃使用 IB Hook ImageView 并尝试在代码中创建它,如下所示: http://cl.ly/QFxs

图像无法正常显示。如果您查看屏幕截图(调试器),您将看到图像和 imageView 都是有效对象。

最佳答案

我认为在这种情况下你不需要使用标签。您可以在 FeedViewCell 中创建 UIImageView 属性,在界面生成器中将其连接起来,然后在

中访问它
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

例如

//在 FeedViewCell 中

    @interface FeedViewCell  : UICollectionViewCell

    @property (weak, nonatomic) IBOutlet UIImageView *imageView;

    @end

//在 Controller 中

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

        FeedViewCell *cell = (FeedViewCell *) [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

        cell.imageView.image = [UIImage imageNamed:[postPhotos objectAtIndex:indexPath.row]];
        return cell;
    }

打开 Storyboard,然后单击助理编辑器按钮,这将打开另一个窗口。打开 feedViewCell.h 并按住 Ctrl 键并单击 imageView 并将其拖动到 .h 文件,该文件将为您提供一个用于创建导出的菜单。您可以将其命名为 imageView 属性。应该是这样。 enter image description here

查看此链接以获取更多信息 http://klanguedoc.hubpages.com/hub/IOS-5-A-Beginners-Guide-to-Storyboard-Connection

关于ios - 从 UICollectionViewCell 实例访问图像时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17655252/

相关文章:

ios - TableView 单元格内的 Collection View 未被调用

ios - 具有不同单元格数量的 viewController 中的多个 Collection View

ios - 使用http方案深度链接iOS

ios - 动画layer.mask如何变化

ios - UICollectionView 仅显示数据集中的第一项

ios - 如何快速调整单元格大小以适应尺寸类别

ios - 如何以编程方式将纵横比约束应用于自定义 UICollectionViewCell?

iphone - 为什么在 viewDidUnload 中将 nil 分配给 IBOutlets?

ios - Xcode 6 中的“对象”选项卡在哪里?

ios - 在 UICollectionView swift 中折叠一个部分的单元格