Reputation: 235
How can I increase my cell height. Also I am increasing cell height from storyboard but it's not working. Note: (Only I want to increase What's New Cells Height)
Code:-
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if let flowLayout = collectionview.collectionViewLayout as? UICollectionViewFlowLayout {
let horizontalSpacing = flowLayout.scrollDirection == .vertical ? flowLayout.minimumInteritemSpacing : flowLayout.minimumLineSpacing
let cellWidth = (view.frame.width - max(0, numberOfCellsPerRow - 1)*horizontalSpacing)/numberOfCellsPerRow
flowLayout.itemSize = CGSize(width: cellWidth, height: cellWidth)
}
return CGSize(width: (self.view.frame.width - 8) / 3.0 , height: (self.view.frame.width - 8) / 3.0)
}
Upvotes: 0
Views: 225
Reputation: 19757
sizeForItemAt
is called for every item in your collection. This code:
if let flowLayout = collectionview.collectionViewLayout as? UICollectionViewFlowLayout {
let horizontalSpacing = flowLayout.scrollDirection == .vertical ? flowLayout.minimumInteritemSpacing : flowLayout.minimumLineSpacing
let cellWidth = (view.frame.width - max(0, numberOfCellsPerRow - 1)*horizontalSpacing)/numberOfCellsPerRow
flowLayout.itemSize = CGSize(width: cellWidth, height: cellWidth)
}
Looks like it belongs to viewDidLoad
, or somewhere else where it would be called just once. Moreover, if I am not mistaken, setting flowLayout.itemSize
is used when all the items have the same size - thus it cannot not be combined with sizeForItemAt
implementation (in other words, I would remove it altogether.
This is what gets applied in the end:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: (self.view.frame.width - 8) / 3.0 , height: (self.view.frame.width - 8) / 3.0)
}
So to change the height of the cells in the given collectionView
just change the height in the returned CGSize
, e.g., to collectionView.frame.height
to fit the collectionView
's height:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: (self.view.frame.width - 8) / 3.0 , height: collectionView.frame.height)
}
Upvotes: 1