Upvote:2

Aprove answer
//define constant value as per your requirement and declare this variables globally
let inset: CGFloat = 10 //define as per your requirement
let minimumInteritemSpacing: CGFloat = 10 //define as per your requirement
let cellsPerRow = 3

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
   let marginsAndInsets = inset * 2 + collectionView.safeAreaInsets.left + collectionView.safeAreaInsets.right + minimumInteritemSpacing * CGFloat(cellsPerRow - 1)
        
   let itemWidth = ((collectionView.bounds.size.width - marginsAndInsets) / CGFloat(cellsPerRow)).rounded(.down)
   
   return .init(width: itemWidth, height: itemWidth)
        
}

Upvote:1

 let spaceBetweenCells: CGFloat = 10
 collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: (collectionView.frame.width - 2* spaceBetweenCells)/3, height: 100)
    }

Credit Goes to: stackoverflow.com

Related question with same questions but different answers