Search code examples
iosswiftuicollectionviewuicollectionviewcelluicollectionviewlayout

UICollectionView BackgroundView Issue


I am trying to add a custom, interactive view behind a UICollectionView (represented by the yellow background in the picture). The easiest way I've found to do this is by using the backgroundView property on my UICollectionView. The only issue is that if a I add spacing between the cells, the background view is visible between the spaces. To combat this, I've made the cell spacing 0, and have mimicked black grid lines by adding a margin around the UIImageViews in the cells (represented by the purple squares) and then making the background of the cells black. This works perfectly for the horizontal spacing above and below the cells, but for some reason the background view is still visible through a narrow vertical line between them. I have made sure that the cell widths are exactly half that of the UICollectionView, and that the minimumLineSpacing and minimumInteritemSpacing are both 0.0.

enter image description here


Solution

  • For anyone who's interested I discovered a solution in this thread here: https://stackoverflow.com/a/55561816/5225013

    This is the code I used from @Asike, slightly modified to fit my use case. It increases the cell widths if their combined calculated widths don't perfectly equal the total width of the collectionView. This occurs on some screen sizes/scales due to decimal places.

    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)
    }