【发布时间】:2017-01-30 23:50:26
【问题描述】:
我有一个集合视图,我希望即使有少量数据也能显示一些单元格。例如,在这张图片中,请注意只有 1 个项目,但所有其他单元格仍以背景颜色显示。
我只知道如何通过伪造用于填充numberOfItemsInSection 中的集合视图的数据量来做到这一点。这是我的示例代码:
class ViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
let itemArray = ["1"]
}
extension ViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
/// Note I can fake more cells here but don't think this is correct way.
return itemArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! FavoritesCollectionViewCell
return cell
}
}
这只需要在有足够的单元格显示在屏幕上之前有效。例如,需要大约 8 个单元格来填满屏幕,一旦数组中有足够的项目来填满屏幕,就不再需要了。
有什么想法吗?
更新 1:
此集合视图将支持添加、删除和排序项目。如果我在numberOfItemsInSection 中添加假数据,不确定这是否会成为问题
【问题讨论】:
标签: ios swift uitableview uicollectionview uicollectionviewcell