crazyhor77
crazyhor77

Reputation: 185

Calculating cell width in UICollectionView inside ContainerView

I have a UICollectionView and I have implemented the delegate to calculate the width of my cells for 0 spacing between cells.

It works great on its own, but when I have it inside a container view less than the size of the device, iOS incorrectly works out the spacing between the cells adding a horizontal space I don't want.

I have verified the width I am using to calculate the cell size is correct, so I'm not sure what is causing the problem.

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let widthPerItem = view.frame.width / itemsPerRow

    return CGSize(width: widthPerItem, height: 60)
}

Upvotes: 0

Views: 1595

Answers (2)

crazyhor77
crazyhor77

Reputation: 185

Ok, the problem was actually related to my uicollectionviewcontroller not correctly sizing to it's parent container view. Changing to a uiviewcontroller with an embedded uicollectionview plus constraints fixed the problem.

Upvotes: 0

vacawama
vacawama

Reputation: 154691

You are calculating your cell size based upon the size of the view. Since the collectionView doesn't take up the full width of the screen, you are getting the incorrect value. Instead, you should base your calculation on the width of the collectionView itself.

Use the bounds of the collectionView instead of the frame of the view:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
  let widthPerItem = collectionView.bounds.width / itemsPerRow

  return CGSize(width: widthPerItem, height: 60)
}

Upvotes: 1

Related Questions