Setting UICollectionView frame at runtime

3.5k Views Asked by At

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
3

There are 3 best solutions below

0
Proton On BEST ANSWER

Try to set frame in viewDidLayoutSubviews

0
Bhadresh Kathiriya On

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))
0
Dave Dempsey On

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()
    }