0

I am programmatically creating a UICollectionView in viewDidLoad and then setting auto layout constraints on it. I need to know exactly what the collection view's width will be after it is displayed to the user, but I need that information in viewDidLoad (cannot use willLayoutSubviews etc).

How do you force layout to occur so I can guarantee the width will update to be the real width in viewDidLoad?

//viewDidLoad:
let collectionView = //...
self.view.addSubview(collectionView)
//add constraints here
let wid = collectionView.frame.size.width //0

//viewDidAppear:
let wid = collectionView.frame.size.width //603

I have tried calling self.view.layoutSubviews() but this didn't resolve the issue entirely. It changed wid to 720 instead of 0, but that's not correct.

I am attempting this in a Today extension, which may differ from a traditional view controller.

Jordan H
  • 52,571
  • 37
  • 201
  • 351

1 Answers1

0

Use viewWillAppear:. The view will have loaded with the correct frame and you can then create the collection view before the view actually displays.

keithbhunter
  • 12,258
  • 4
  • 33
  • 58
  • I cannot use `willWillAppear` because this affects the behavior of my extension undesirably. What I'm changing based on the width must be set before `viewWillAppear` and only set once. – Jordan H Mar 08 '15 at 00:10
  • Are you setting the width to a certain value? Or are you setting the autolayout constraints based on it's surrounding views? – keithbhunter Mar 08 '15 at 00:12
  • I'm changing an auto layout constraint constant after performing a calculation using the collection view width. The undesirable behavior of doing that in `viewWillAppear` is the extension grows in height while it's loading then once it's done loading it shrinks. I need to set it earlier so it's always the same height. – Jordan H Mar 08 '15 at 00:14
  • The width of the collection view is dynamic - whatever the width of the Today view is for the device it's running on (it has leading and trailing to the superview. – Jordan H Mar 08 '15 at 00:16
  • Also on the iPad, the width reported in `viewWillAppear` isn't the width reported in `viewDidAppear` - it's off by quite a bit. – Jordan H Mar 08 '15 at 00:21