0

I have instantiated a UINavigationController with a custom view controller. Its view contains a button that, when tapped, will have the navigation controller push the view of a different custom view controller into view:

@IBAction func showVC(sender: AnyObject) {
    let vc = MyOtherViewController()
    navigationController?.pushViewController(vc, animated: true)
}

In MyOtherViewController's viewWillAppear() function, I see that the view has not be resized to fit in the view hierarchy.

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    print("view: \(view)")
}

The output from the print() function is:

view: <UIView: 0x7f9432719bd0; frame = (0 0; 600 600); autoresize = W+H; layer = <CALayer: 0x7f9432717cc0>>

As you can see, the size of the view is still 600 x 600 at this point, which is the original size from the .xib file. I haven't adjusted the size of the view in the .xib because the view will be shown on various iPhone and iPad displays.

My dilemma is that I need the final dimensions of the view as I need to construct some NSLayoutConstraints based on the width of the view.

What is the recommended approach for having the view resized? Is it wrong to expect the view to be resized by the time -viewWillAppear() is invoked?

Jason Barker
  • 3,020
  • 1
  • 17
  • 11

1 Answers1

1

Is it wrong to expect the view to be resized by the time -viewWillAppear() is invoked?

Yes. You can be certain that it will be resized by the time viewDidAppear. But that might be too late for your purposes. The event you are looking for is probably viewWillLayoutSubviews or viewDidLayoutSubviews. This will be called many times in the future, so if you want to perform modifications only once at this time, use a boolean flag:

var didSetUp = false
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    if self.didSetUp { return }
    self.didSetUp = true
    // ... do stuff ...
}
matt
  • 515,959
  • 87
  • 875
  • 1,141
  • However, I don't like the sound of this: "I need to construct some NSLayoutConstraints based on the width of the view". If you think you need to know the width of the view in order to construct your layout constraints, you are doing it wrong! The whole point of layout constraints is that you do _not_ need to know any actual numbers, as everything is determined by _relationships_. – matt May 17 '16 at 23:47
  • to properly build **horizontal paging** into a `UIScrollView` with auto layout, you _**need**_ to know the width of the view. – Jason Barker May 18 '16 at 07:18