通过Xib将UICollectionViews添加到自定义UITableViewCell

我惊讶地发现在UITableViewCell中实现UICollectionView有多少障碍。 因此,本教程位于此处,希望它可以节省大量时间。

注意:本教程不适合初学者。 假定您了解tableViews并使用xib文件创建自定义单元格。

另外,我不描述任何有关视觉组件的内容。

1)将UICollectionView添加到Xib TableViewCell

  1. 将UICollectionView拖到TableViewCell Xib中
  2. 添加约束
  3. 并发现您无法将CollectionViewCells添加到新添加的UICollectionView中:)

事实证明,您需要一个单独的文件来放置要显示的任何集合视图单元格。 (当您的UICollectionView在Xib文件中时)

2)将UICollectionViewCell和Xib文件添加到您的项目中

图片

您可以在“集合视图”单元格Xib单元中执行任何操作(添加标签,图像等),出于本教程的目的,我们在此不再赘述。

确保为您的单元格提供一个resuableIdentifier。

图片

3)确认您的TableViewCell类具有UICollectionView数据源和代理协议。

步骤1:返回tableViewCells Xib文件。

图片

步骤2:从您的collectionView拖动到“文件的所有者”,然后选择dataSource,然后委派。

图片

步骤3:从collectionView拖动到TableViewCell类并创建IBOutlet

图片

步骤4:验证您的TableViewCell类UICollectionView数据源和代理协议是否符合。

class TableViewCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource { @IBOutlet weak var collectionView: UICollectionView! override func awakeFromNib() { super.awakeFromNib() // Initialization code self.collectionView.dataSource = self self.collectionView.delegate = self self.collectionView.register(UINib.init(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "collectionViewID") } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 15 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionViewID", for: indexPath as IndexPath) as! CollectionViewCell return cell } } 

代码说明:

  1. 将UICollectionViewDelegate和UICollectionViewDataSource添加到类描述中
  2. 在awakeFromXib中使数据源collectionView和委托= self
  3. 添加函数numberOfItemsInSection
  4. 添加函数cellForItemAt
  5. 创建一个将您的reuseIdentifier作为自定义单元格的单元格。

故障排除步骤:

  1. 我的标识符是否已分配并正确?
  2. 我是否已从我的collectionView拖动到Xib文件中的文件所有者?

如有疑问,请在评论中写。

如果这对您有所帮助或将来会有所帮助,就像。

我希望有人可以节省很多时间。

Source: https://habr.com/ru/post/zh-CN449478/


All Articles