UICollectionView BackgroundView 问题

UICollectionView BackgroundView Issue

我正在尝试在 UICollectionView 后面添加一个自定义的交互式视图(图中以黄色背景表示)。我发现最简单的方法是在 UICollectionView 上使用 backgroundView 属性。唯一的问题是,如果我在单元格之间添加间距,则背景视图在空间之间可见。为了解决这个问题,我将单元格间距设置为 0,并通过在单元格中的 UIImageView 周围添加边距(由紫色方块表示)然后将单元格的背景设为黑色来模仿黑色网格线.这对于单元格上方和下方的水平间距非常有效,但由于某种原因,背景视图仍然可以通过它们之间的一条窄垂直线看到。我已经确保单元格宽度恰好是 UICollectionView 的一半,并且 minimumLineSpacingminimumInteritemSpacing 都是 0.0.

我创建了与您相同的场景。使用以下代码对我来说效果很好。

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    @IBOutlet weak var collectionView: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let backView = UIView(frame: self.collectionView.bounds)
        backView.backgroundColor = UIColor(red: 0.9372549057, green: 0.3490196168, blue: 0.1921568662, alpha: 1)
        self.collectionView.backgroundView = backView
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 30
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
        cell.backgroundColor = UIColor(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1)
        cell.layer.borderWidth = 5.0
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: collectionView.bounds.width / 2, height: collectionView.bounds.width / 2)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 100, left: 0, bottom: 100, right: 0)
    }
}

唯一的一点是,我使用单元格的 borderWidth 进行说明。您可以根据您的要求进行更改。

对于任何感兴趣的人,我在这里的这个线程中发现了一个解决方案:

这是我使用的来自@Asike 的代码,稍作修改以适合我的用例。如果它们的组合计算宽度不完全等于 collectionView 的总宽度,它会增加单元格宽度。由于小数位的原因,在某些屏幕上会出现这种情况 sizes/scales。

public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let columns = 2
    let width = Int(collectionView.bounds.width)
    let side = width / columns
    let rem = width % columns
    let addOne = indexPath.row % columns < rem
    let ceilWidth = addOne ? side + 1 : side
    return CGSize(width: ceilWidth, height: side)
}