I am using a collection view with different cell sizes in vertical scroll mode. I want the cell to appear like these as shown in the image.
But the collection view cell appears like this with extra space on top.
Below is the code from project:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
return self.allProducts.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "demoItem", for: indexPath) as! ItemCollectionViewCell
let item = allProducts[indexPath.row]
cell.lbl_name.text = item.title
cell.lbl_price.text = "$ " + item.price
cell.imgView.image = imgArray[indexPath.row % imgArray.count]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.row % 3 == 0
{
return CGSize(width: collectionView.frame.size.width/2, height: 200)
}
else if indexPath.row % 2 == 0
{
return CGSize(width: collectionView.frame.size.width/2, height: 225)
}
return CGSize(width: collectionView.frame.size.width/2, height: 250)
}
How do I fix the space above cell issue.
Note: I have tried setting automaticallyEdgeInset to false and also manually changed contentInsets but nothing happened.
It looks to me like you’re using a typical flow layout, which creates rows with a height of the tallest item in the row and vertically centers all the items in that row. My guess is the cells just don’t take up all that space (maybe because of autolayout and the image sizes?).
Whatever the cause, it look like you’re trying to position the cells as closely as you can from top to bottom, ignoring rows.
I recent made one of these, quite successfully by following this guide from Ray Wenderlich