2014-10-06 70 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: 

这应该然后保证电池组的任何网点:)

相关问题