ios - 为什么单元格有效但创建后其元素为零

标签 ios uicollectionview uicollectionviewcell

这个问题适用于 tableView 和 collectionView。

让我们谈谈使用原型(prototype)单元格的 Collection View 。

假设原型(prototype)单元格分配给 MyCollectionViewCell 类。

假设这个类有两个属性:countryNamecountryImage(分别是一个标签和一个 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.countryImagecell.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/

相关文章:

ios - Appium::TouchAction.new.tap 无法正常工作

ios - 为什么我只能在 TableView Swift 中展示我的第一部分?

ios - 在更改视觉状态时取消选择 collectionView 中的所有单元格

ios - 集合单元格内容大小

ios - UITableView 只显示 10 个单元格/行

ios - 使用 AFNetworking 2 和可达性没有互联网连接警报

uitableview - UITableViewCell 动态布局中的 Swift UICollectionView 无法更改单元格高度

ios - UICollectionView重新加载数据Swift 4

uicollectionview - 带标题的两列 UICollectionView

ios - 在 Collection View 的 cellForItemAtIndexPath 方法中更改框架