Aligning collection view cells to fit exactly 3 per row

前端 未结 5 1747
深忆病人
深忆病人 2020-12-23 22:01

I am trying to make a collection view of images, so that there are 3 per row, with no spacing in between.

My collection view data sources are:

func n         


        
5条回答
  •  别那么骄傲
    2020-12-23 22:39

    1- You have to conform to UICollectionViewDelegateFlowLayout

    2- You should implement collectionView(_:layout:sizeForItemAt:) method, as follows:

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let screenWidth = UIScreen.main.bounds.width
        let scaleFactor = (screenWidth / 3) - 6
    
        return CGSize(width: scaleFactor, height: scaleFactor)
    }
    

    Assuming that the minimum spaces are 8 -for example-,

    the output should be three items for each row, square sized.

    Remark: If you want to set the spaces between the cells to be zero, then scaleFactor should be:

    let scaleFactor = (screenWidth / 3)
    

    Hope this helped.

提交回复
热议问题