2013-07-15 159 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...,那麼你需要將其刪除。故事板自動處理此註冊。