从未在类中调用 cellForItemAt 扩展 UICollectionViewController

Posted

技术标签:

【中文标题】从未在类中调用 cellForItemAt 扩展 UICollectionViewController【英文标题】:cellForItemAt never called in a class extends UICollectionViewController 【发布时间】:2016-11-02 04:06:41 【问题描述】:

我按照video 创建了 UICollectionViewController,但集合单元格未按预期显示。我添加了一些打印消息,结果发现 numberOfItemsInSection 被调用,但 cellForItemAt 函数从未被调用。另外,在 viewDidLoad 方法中,我打印出了 collectionView?.contentSize 它是 (0.0, 0.0)。不知道有什么问题。谁能帮忙解释一下?

更多: 我发现问题可能是我没有使用pushViewController导航而是使用performSegue,所以我没有像视频那样设置UICollectionDelegateFlowLayout...有什么办法解决吗?

【问题讨论】:

你是怎么写collectionView(cellForItemAt)的?你有一些代码吗? ` override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "message cell", for: indexPath) cell.backgroundColor = UIColor .blue print("cell created") return cell ` 你能把这个放在你的问题中吗? 无论是使用 segue 还是 pushViewController,对集合视图中的单元格都没有影响 【参考方案1】:

您是否确保函数 numberOfItemsInSection 至少返回 1 或更多?如果您可以粘贴一些代码,将会很有帮助。

【讨论】:

【参考方案2】:

确保您已设置 UICollectionView 的 Datasource 和 Delegate。

yourcollectionview.delegate = self
yourcollectionview.dataSource = self

【讨论】:

以上是关于从未在类中调用 cellForItemAt 扩展 UICollectionViewController的主要内容,如果未能解决你的问题,请参考以下文章

在类中调用类

如何让方法在类中调用另一个方法?

如何在类中调用函数?

reloadData 没有调用 cellForItemAt

在类中引用函数时出现“调用没有匹配函数”

Swift DRY collectionView(_ cellForItemAt) 调用