2017-04-25 22 views
0

我正在使用自定義CollectionView單元實現自定義集合視圖。自定義CollectionViewCell屬性爲零

這是我的CollectionView實現。

- (void)setUpCollectionView{ 
    [self.view setNeedsLayout]; 
    [self.view layoutIfNeeded]; 

    [self.vwCarCollection setDataSource:self]; 
    [self.vwCarCollection setDelegate:self]; 

    [self.vwCarCollection registerClass:[FindMyCarCell class] forCellWithReuseIdentifier:@"FindMyCarCell"]; 
    [self.vwCarCollection setBackgroundColor:[UIColor redColor]]; 

    [self.vwCarCollection reloadData]; 
    [self.vwCarCollection reloadInputViews]; 
} 

我在「ViewDidLoad」上調用了這個函數。

這裏是我實施UICollectionViewDataSource

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{ 
    FindMyCarCell *cell = (FindMyCarCell *)[self.vwCarCollection dequeueReusableCellWithReuseIdentifier:@"FindMyCarCell" forIndexPath:indexPath]; 
    cell.vwImgMain.image = [UIImage imageNamed:@"sample_car"]; 
    cell.lblCarNo.text = @"GH2334343"; 
    return cell; 
} 

當我調試我的代碼,細胞實例有這樣

<FindMyCarCell: 0x78645b30; baseClass = UICollectionViewCell; frame = (302 50; 221 180); layer = <CALayer: 0x786a07a0>> 

但是,當我嘗試更新我的自定義單元格的ImageView的,它只是返回我的圖像視圖爲零。 我的實現出了什麼問題。有人可以建議我嗎?謝謝。

+0

FindMyCarCell * cell =(FindMyCarCell *)[self.vwCarCollection dequeueReusableCellWithReuseIdentifier:@「FindMyCarCell」forIndexPath:indexPath];用collectionView代替self.vwCarCollection ..然後嘗試 – ajjjjjjjj

+0

你可以顯示包含在FindMyCarCell中創建'vwImgMain'的方法嗎? – nynohu

+0

有一個很好的教程聽到,但它很快,但概念類似於obj-c,只是通過這個http://randexdev.com/2014/08/uicollectionviewcell/ –

回答

0

將圖像視圖添加到單元格時可能會出現一些錯誤。如果您在Storyboard中創建了單元格,則不要在viewDidLoad中註冊您的單元類。相反,在Storyboard中設置重用標識符,或者使用自定義集合視圖單元類的框架方法將圖像視圖添加到init中。

0

嘗試致電viewDidApppear

[self.vwCarCollection registerClass:[FindMyCarCell class] forCellWithReuseIdentifier:@"FindMyCarCell"]; 
+0

我爲我的自定義單元格使用了單獨的xib。 –

+1

所以你需要使用'registerNib',而不是'registerClass'。 – nynohu

+0

你檢查了xib中的reuseIdentifier嗎? – KKRocks

0

如果使用的是廈門國際銀行文件,調用

[self.vwCarCollection registerNib:[UInib nibWithNibName:@"FindMyCarCell" bundle:nil] forCellWithReuseIdentifier:@"FindMyCarCell"]; 

而不是

[self.vwCarCollection registerClass:[FindMyCarCell class] forCellWithReuseIdentifier:@"FindMyCarCell"]; 

的原因是,當你調用registerClass,你FindMyCarCell將通過調用initWithFrame被initiallized,你沒有通過這種方式實現init你的imageView。當你調用registerNib時,堆棧調用將通過調用awakeFromNib來初始化你的FindMyCarCell(所以imageView將被創建)。