用少量数据显示单元格背景颜色

时间:2017-01-30 23:50:26

标签: ios swift uitableview uicollectionview uicollectionviewcell

我有一个集合视图,即使有少量数据,我也希望显示一些单元格。例如,在此图片中,请注意如何只有1个项目,但所有其他单元格仍然显示为背景颜色。

collectionView

我知道如何通过伪造用于填充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

中添加假数据,不确定这是否会成为问题

2 个答案:

答案 0 :(得分:0)

  

注意我可以在这里伪造更多的细胞,但不要认为这是正确的方法

为什么不呢?如果你想要空单元格,请求空单元格!它不是假装"一点都不。

另一种方法是(实时)绘制一个看起来的网格,就像空网格一样,并将其显示为集合视图的背景。

答案 1 :(得分:0)

我会做类似的事情:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return max(itemArray.count, 8)
}


func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! FavoritesCollectionViewCell

    if (indexPath.row <= itemArray.count) {
        // just guessing here how your setting image
        cell.image = itemArray[indexPath.row].image
    }

    return cell
}

我认为你是在正确的轨道上,而不是假装 - 你只是设置单元格并设置最少数量的元素