swiftuicollectionviewuicollectionviewcelluicollectionviewdelegateflowlayout

UICollectionView with 3 columns doesn't produce the desired result


I'm testing this on iPhone XR simulator. I have 3 rows of images and I want them displayed in 3 columns, 2 points distance top, left, right and bottom. This used to work but for some reason it doesn't now.

extension ProfileVC : UICollectionViewDelegateFlowLayout {
override func size(forChildContentContainer container: UIContentContainer, withParentContainerSize parentSize: CGSize) -> CGSize {
    return CGSize(width: collectionView.bounds.width / 3, height: collectionView.bounds.width / 3)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}

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

This is my result:

enter image description here


Solution

  • Try implementing sizeForItemAt indexPath method to fix your collection view for a three columns only with item size dynamically based on screen width. get the screen width or collection view width, then subtract your preferred spaces (8) then divide by 3 (3 columns). Also, from your storyboard or nib file set minSpacing for lines = 2 and section insets for top = 2 and comment your above methods and implement only this method

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = (collectionView.frame.width - 8) / 3
        return CGSize(width: width, height: width)
    }