2013-07-15 162 views
2

的情况下访问图片我下面这个教程有一些修改为我的项目:http://www.appcoda.com/ios-programming-uicollectionview-tutorial/麻烦从UICollectionViewCell

我试图得到的UIImageView的实例IB为我创建。

这里是我的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 *)[细胞viewWithTag:100];返回为零。无论如何,使用viewWIthTag方法对我来说似乎很奇怪,但在调试器中,我看不到imageView是UICollectionViewCell的子视图。如果你看一下这个调试屏幕,你可以看到,电池不会出现任何的UIImageView子视图:

enter image description here

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

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

感谢您的任何建议!

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

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

回答

1

我不认为你需要在这种情况下使用标签。您可以在Interface Builder创建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; 
    } 

打开故事板,然后单击助理编辑按钮,其中wi会带来另一个窗口。在那里打开feedViewCell.h,然后按住Ctrl键并单击imageView并将其拖到.h文件中,该文件将为您提供一个菜单来创建插口。您可以将它命名为imageView属性。应该是这样的。 enter image description here

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

+0

我想我的概率是我不知道如何在IB中连线.... –

+0

我更新了我的答案。我希望有所帮助。 – Yan

1

如果您呼叫self.collectionView registerClass...,那么你需要将其删除。故事板自动处理此注册。