Ios 显示包含少量数据的单元格背景色

Ios 显示包含少量数据的单元格背景色,ios,swift,uitableview,uicollectionview,uicollectionviewcell,Ios,Swift,Uitableview,Uicollectionview,Uicollectionviewcell,我有一个集合视图,我希望即使有少量数据也能显示一些单元格。例如,在这张图片中,请注意,只有一个项目,但所有其他单元格仍以背景色显示 我知道如何做到这一点,只是通过在numberOfItemsInSection中伪造用于填充集合视图的数据量。这是我的示例代码: class ViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView! let itemArray =

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

我知道如何做到这一点,只是通过在
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

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

为什么不呢?如果你想要空单元格,就要空单元格!这根本不是“伪造”


另一种方法是(实时)绘制一个类似于空网格的网格,并将其显示为集合视图的背景。

我只需执行以下操作:

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
}
func collectionView(collectionView:UICollectionView,numberofitemsinssection:Int)->Int{
返回最大值(itemArray.count,8)
}
func collectionView(collectionView:UICollectionView,cellForItemAt indexPath:indexPath)->UICollectionViewCell{
让cell=collectionView.dequeueReusableCell(带有reuseidentifier:“cell”,for:indexPath)作为!FavoritesCollectionViewCell

如果(indexPath.row)我更新了我的问题,请让我知道这是否是一个问题-之前应该已经提到过它那么我的其他想法呢?你可以提供空单元格作为“装饰视图”,或者只是作为背景图。我想那真的是唯一的方法-谢谢!你好,马特,我有一个关于悬赏的AVFoundation问题,从你的书上看,你似乎是这方面的专家,你能看一下吗: