2

I am trying to set the frame of my UICollectionView at runtime.

I tried using

mainCollectionView.frame = CGRect(x: 20, y: 20, width: self.view.frame.width-20, height: self.view.frame.width-20)

in my viewDidLoad but unfortunately it will always stay as in IB. I am not yet using constraints.

Otherwise resizing my cells is working in cellForItem:

 collectionCell.frame.size.width = self.view.frame.width/8 * 3
JVS
  • 2,592
  • 3
  • 19
  • 31
  • display your correct set collectionview screen. – Bhadresh Kathiriya Jun 29 '16 at 09:17
  • Possible duplicate of [How to set UIView size to match parrent without constraints programmatically](http://stackoverflow.com/questions/37725406/how-to-set-uiview-size-to-match-parrent-without-constraints-programmatically) – Yury Jun 29 '16 at 09:18
  • 1
    The answer was already posted but deleted: it is important to set everything in viewDidLayoutSubviews – JVS Jun 29 '16 at 09:27
  • 1
    @ShadowOf this is not a duplicate of your provided link – Nitin Gohel Jun 29 '16 at 09:28
  • 1
    Changing the frame size in the viewDidLoad is not safe because most of the times, view are not fully functional according to the current superview. Instead of viewDidLoad, you change the frame size inside viewWillAppear() or viewDidAppear(). viewDidLayoutSubviews() is the safest place. – ranjit.x.singh Jun 29 '16 at 09:30

3 Answers3

2

Try to set frame in viewDidLayoutSubviews

Proton
  • 1,335
  • 1
  • 10
  • 16
1

you are wrong write height because you are set width at height.

try this line without navigation bar:

 mainCollectionView.frame = CGRect(x: 20, y: 20, width: UIScreen.mainScreen().bounds.size.width - (20 * 2), height: UIScreen.mainScreen().bounds.size.height - (20 * 2))
Bhadresh Kathiriya
  • 3,147
  • 2
  • 21
  • 41
0

Run the following in one of the LayoutSubviews overrides. This will tell collection view to update its frame.

   override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        mainCollectionView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
        mainCollectionView.collectionViewLayout.invalidateLayout()
    }
Dave Dempsey
  • 117
  • 3
  • 7