2014-10-06 59 views
0

此問題適用於tableViews和collectionViews。爲什麼一個單元格有效,但其元素在創建後爲零

讓我們談談使用原型單元的集合視圖。

假設原型單元格被分配給MyCollectionViewCell類。

假設這個類有兩個屬性:countryNamecountryImage(分別是一個label和一個imageView)。

爲什麼我不能在此方法中爲名稱和國家分配值?什麼是解決這個問題的最好方法?

在此方法...

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

    MyCollectionViewCell *cell = (MyCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath]; 

    NSArray *section = self.arrayData[indexPath.section]; 

    NSDictionary *itemOnSection = section[indexPath.row]; 

    // Configure the cell 
    UIImage *image = [UIImage imageNamed:itemOnSection[@"image"]]; 
    NSString *name = itemOnSection[@"name"]; 

    cell.countryImage.image = image; 
    cell.countryName.text = name; 

    return cell; 
} 

究竟會用這種方法出現的情況是細胞將是一個有效的對象,但cell.countryImagecell.countryNamenil

我不明白的是:如果單元格存在並且是根據調試器的有效對象,爲什麼它的元素沒有被初始化。什麼是解決這個問題的最好方法?

這是MyCollectionViewCell.h

@interface MyCollectionViewCell : UICollectionViewCell 

@property (weak, nonatomic) IBOutlet UIImageView *countryImage; 
@property (weak, nonatomic) IBOutlet UILabel *countryName; 


@end 

的出口被連接到所述原型細胞和原型細胞中的元素具有此類分配。

MyCollectionViewCell.m沒有任何內容。

回答

0

在UICollectionView文檔中有關於單元格的部分。

根據該細胞:

返回值在相應的索引路徑或零如果 所述細胞是不可見的或indexPath超出範圍的單元對象。

也許你有

MyCollectionViewCell

設置資源

你首先創建屬性的問題是電池

@property (nonatomic, retain) NSString *countryNameTitle; 

比的方法來設置名稱

//method to set name that should be called from cellForItemAtIndexPath 
-(void)setCountryName 
{ 
    if ([countryNameTitle length] != 0) 
    { 
    countryName.text = countryNameTitle; 
    } 
} 

而不是從委託

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

    MyCollectionViewCell *cell = (MyCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath]; 

    NSArray *section = self.arrayData[indexPath.section]; 

    NSDictionary *itemOnSection = section[indexPath.row]; 

    // Configure the cell 
    UIImage *image = [UIImage imageNamed:itemOnSection[@"image"]]; 
    NSString *name = itemOnSection[@"name"]; 

    cell.countryImage.image = image; 
    cell.countryNameTitle = name; 
    [cell setCountryName]; 


    return cell; 
} 
+0

好的,但細胞不是零。無是單元格的標籤和imageView。這是我不明白的。如果單元格對象爲何它的屬性爲零? – SpaceDog 2014-10-06 11:00:42

+0

顯示你的MyCollectionViewCell – 2014-10-06 11:01:23

+0

我已經添加了更多代碼的問題,但它可能是不可見的,直到有更多的信譽的人批准它。我所擁有的就是連接到MyCollectionViewCell類的屬性和分配給該類的原型單元格的imageView和countryName標籤的出口。 – SpaceDog 2014-10-06 11:23:42

1

你是如何註冊的觀點集名稱由集合視圖中使用?

如果你想使用筆尖/廈門國際銀行所定義的小區,你必須:

registerNib:forCellWithReuseIdentifier: 

,而不是

registerClass:forCellWithReuseIdentifier: 

這應該然後保證電池組的任何網點:)

相關問題