Skip to content

Instantly share code, notes, and snippets.

@abhi21git
Last active November 1, 2022 07:54
Show Gist options
  • Save abhi21git/d0aadde3f14ecf464fdc6b0cf8849f98 to your computer and use it in GitHub Desktop.
Save abhi21git/d0aadde3f14ecf464fdc6b0cf8849f98 to your computer and use it in GitHub Desktop.
Dynamic cell size based on screenWidth
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let totalAvailableWidth = collectionView.bounds.width
let padding: CGFloat = 25
let interSpace: CGFloat = 15
let numOfCellInaRow: CGFloat = 3
let cellWidth: CGFloat = (totalAvailableWidth - (padding * 2) - (interSpace * (numOfCellInaRow - 1))) / numOfCellInaRow
/// padding * 2 = leading + trailing space, (interSpace * (numOfCellInaRow - 1)) = totalInterspacing as 3 cells will have 2 interspace
let cellSize = CGSize(width: cellWidth, height: cellWidth)
return cellSize
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment