view.bounds.height calculation inconsistent on Navigation Controller

I was wondering if anyone has come across this before. I am using a Navigation controller in my project, and I noticed that when I first push a view controller on it, view.bounds.height calculation compensates for the status bar. However, when I closed out of the project and tried the same push again, the view.bounds.height calculation now does not compensate for the status bar.


For example, if the actual view.bounds.height without the status bar is 400:

On first load: view.bounds.height = 380 (400 - 20)

On second load: view.bounds.height = 400 (What I want)


Each time, view.bounds.calculation is done in ViewDidLoad.


I am using the calculation to set up other views, so I want it to be consistent. Is there anyway I can make sure that the calculation is done without compensating for the status bar height? I thought maybe putting the view calculation code later in the view controller cycle will help, but I've always put view bounds calculations in ViewDidLoad without any problem. If this is not good practice, please let me know.

Accepted Answer

A view isn't going to know its final bounds until (a) it's been added to the view hierarchy, and (b) autolayout has had a chance to run. The view isn't part of the view hierarchy at viewDidLoad time. From that perspective, the correct place to get the actual view bounds would be at viewDidAppear time.


There might actually be reasons why the view sometimes has the "correct" size at viewDidLoad time. For example, if state restoration is in effect, you might see the design-time size the first time the view is loaded, and the previous run-time size subsequently. However, the behavior is likely implementation dependent, and shouldn't be relied on.


If you're calculating things based on the view's actual bounds, you might be better served by looking for a different intervention point, since you'd presumably want to re-calculate whenever the view's size changed, not just when the view is initially sized. So, for example, you might use 'viewWillTransition(to:with:)' instead. Or possibly 'viewWillLayoutSubviews()'.

Thank you for your detailed explanation!

view.bounds.height calculation inconsistent on Navigation Controller
 
 
Q