0

When debugging custom UICollectionView via View Debug it's width is 829, but when it's width is accessed via code it's width is 820. What am I missing?

Visual debug:

enter image description here

Code:

func collectionView(_ collectionView: UICollectionView, layout: UICollectionViewLayout, sizeForItemAt: IndexPath) -> CGSize
    {
        let widthForCulculation = self.frame.size.width // 820.0
        ...
        return CGSize(width: segmentWidth, height: segmentHeight)
    }
a.masri
  • 2,439
  • 1
  • 14
  • 32
Luda
  • 7,282
  • 12
  • 79
  • 139
  • Check spaces between cells look here https://stackoverflow.com/a/35656724/9315978 – a.masri Jun 14 '18 at 09:33
  • You should be using `collectionView.bounds.size.width` instead of `self.frame.size.width`. – vacawama Jun 14 '18 at 09:37
  • @vacawama : The only difference between bounds and frame is origin, frame's value is calculated with respect to/relative to parentView where as in case of bounds its always calculated relative to itself. hence bounds origin is always 0,0. But no matter which one u use, height n width will always be same. So in this case using frame or bounds will not make any difference. Lemme know if am wrong – Sandeep Bhandari Jun 14 '18 at 09:45
  • @SandeepBhandari, that's true if 1) you're looking at the `bound`s and `frame` of the same object, 2) the object is not rotated (if rotated, frame gets wider, but bounds does not change). But, in this case `self` refers to the `view` of the viewController and `collectionView` is one of its subviews so it's not reasonable to always expect them to be the same size. – vacawama Jun 14 '18 at 09:51
  • @vacawama self.frame.size.width and collectionView.bounds.size.width are the same – Luda Jun 14 '18 at 09:54
  • @vacawama : Ohhh god sorry I did not realize that it was `collectionView.bounds.size.width` I thought u were asking OP to use `self.bounds.size.width` instead of `self.frame.size.width` . Feel so stupid :| But then thank you I did not know on rotation bounds will not change :) Learnt something new :) Thanks – Sandeep Bhandari Jun 14 '18 at 09:54

1 Answers1

1

Pretty hacky way, but try to invalidate layout when layouting subviews

var width : CGFloat = 0
override func layoutSubviews() {
   super.layoutSubviews()
   if (self.width != self.frame.size.width)
   {
       self.width = self.frame.size.width
       self.collectionViewLayout.invalidateLayout()
   }
}
Yanny
  • 490
  • 4
  • 16