【问题标题】:Show cell background color with small amounts of data使用少量数据显示单元格背景颜色
【发布时间】: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


    【解决方案1】:

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

    为什么不呢?如果您想要空单元格,请要求空单元格!这根本不是“伪装”。

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

    【讨论】:

    • 我更新了我的问题,如果有问题请告诉我 - 之前应该提到过
    • 那么我的另一个想法呢?您可以将空单元格提供为“装饰视图”,或者仅作为背景图。
    • 我认为那真的是唯一的出路 - 谢谢!
    • 你好,matt,我有一个关于 AVFoundation 的问题,从你的书中看来你是这方面的专家,你能看看:stackoverflow.com/questions/43282423/…
    【解决方案2】:

    我会这样做:

    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
    }
    

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

    【讨论】:

      猜你喜欢
      • 2018-06-30
      • 2022-12-12
      • 2015-11-29
      • 1970-01-01
      • 2011-04-03
      • 1970-01-01
      • 1970-01-01
      • 2014-10-08
      • 1970-01-01
      相关资源
      最近更新 更多