这个问题适用于 tableView 和 collectionView。
让我们谈谈使用原型(prototype)单元格的 Collection View 。
假设原型(prototype)单元格分配给 MyCollectionViewCell
类。
假设这个类有两个属性:countryName
和 countryImage
(分别是一个标签和一个 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 将是一个有效对象,但 cell.countryImage
和 cell.countryName
将为 nil
。
我不明白的是:如果单元格存在并且根据调试器是有效对象,为什么它的元素没有被初始化。解决这个问题的最佳方法是什么?
这是 MyCollectionViewCell.h
@interface MyCollectionViewCell : UICollectionViewCell
@property (weak, nonatomic) IBOutlet UIImageView *countryImage;
@property (weak, nonatomic) IBOutlet UILabel *countryName;
@end
socket 连接到原型(prototype)单元上的元素,并且原型(prototype)单元分配了此类。
MyCollectionViewCell.m 没有任何内容。
最佳答案
您如何注册 View 以供 Collection View 使用?
如果你想使用在 nib/xib 中定义的单元格,你必须:
registerNib:forCellWithReuseIdentifier:
相对于
registerClass:forCellWithReuseIdentifier:
这应该确保单元设置任何 socket :)
关于ios - 为什么单元格有效但创建后其元素为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26214097/