Unable to set frame correctly before viewDidAppear
Solution 1:
viewDidLoad is called when the class is loaded however no ui elements have been initialised and therefore any attempt to reference them will be overwritten or unavaliable during the initialisation process which happens between the viewDidLoad and viewDidAppear calls. Once all ui element have been initalised and drawn viewDidAppear is called.
viewDidLoad - Called after the controller's view is loaded into memory
At this point the view isn't within the view hierarchy.
viewWillAppear - Notifies the view controller that its view is about to be added to a view hierarchy.
Again, the view is yet to be added to the view hierarchy.
viewDidAppear - Notifies the view controller that its view was added to a view hierarchy.
Only then is the view added to the view hierarchy.
Update
The viewDidLayoutSubviews
is the most appropriate place to modify the UI before it actually appears on the screen.
viewDidLayoutSubviews - Notifies the view controller that its view just laid out its subviews.
Solution 2:
See this thread When is layoutSubviews called?
When use autolayout, framework do not call layoutSubviews automatically. That is very important. From ref:
- init does not cause layoutSubviews to be called (duh)
- addSubview: causes layoutSubviews to be called on the view being added, the view it’s being added to (target view), and all the subviews of the target. ...
If you add subview in viewDidLoad, layoutSubviews called before viewDidAppear, and you can get the correct size of subviews. But if you do nothing, layoutSubviews will be called after viewDidAppear. It's up to your code.