2

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

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

这是我的 IB 的截图:

在此处输入图像描述

我有一个名为 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 的子视图的迹象。如果您查看此调试屏幕,您会看到该单元格似乎没有任何 UIImageView 子视图:

在此处输入图像描述

但是我看到 2 UIImageViews 作为 CollectionView 的子视图。

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

感谢您的任何建议!

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

图像无法正确显示。但是,如果您查看屏幕截图(调试器),您会看到图像和 imageViews 都是有效的对象。

4

2 回答 2

1

如果您正在调用self.collectionView registerClass...,则需要将其删除。情节提要自动处理此注册。

于 2014-01-28T08:33:08.553 回答
1

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

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

例如

// 在 FeedViewCell 中

    @interface FeedViewCell  : UICollectionViewCell

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

    @end

// 在控制器中

    - (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;
    }

打开故事板,然后单击将打开另一个窗口的助手编辑器按钮。打开 feedViewCell.h 并 ctrl+单击 imageView 并将其拖到 .h 文件中,该文件将为您提供创建出口的菜单。您可以将其命名为 imageView 属性。应该是这样的。 在此处输入图像描述

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

于 2013-07-15T13:50:56.507 回答