UICollectionView BackgroundView问题

时间:2019-05-12 15:05:29

标签: ios swift uicollectionview uicollectionviewcell uicollectionviewlayout

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

enter image description here

2 个答案:

答案 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进行说明。您可以根据需要进行更改。

enter image description here

答案 1 :(得分:0)

对于有兴趣的人,我在此线程中找到了一种解决方案:https://stackoverflow.com/a/55561816/5225013

这是我在@Asike中使用的代码,对其进行了略微修改以适合我的用例。如果它们的组合计算出的宽度不完全等于collectionView的总宽度,则会增加像元的宽度。由于小数点后,这种情况在某些屏幕尺寸/比例上会发生。

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)
}
相关问题