Reputation: 1155
I have been trying to find some advice on the best practice method of laying out screen elements in my swift project. I've found a number of posts that tell me where I can lay things out, but I am keen to find out what whether my approach is correct / acceptable or not.
A few of my apps have reasonably complex layouts, e.g. the one I'm working on now has a UITabViewController
with the first tab including a UINavigationViewController
, and the navigation view containing a UIPageViewController
. Due to having a range of issues with correctly displaying screen elements (e.g. elements appearing behind other elements, elements appearing with the incorrect screen sizes etc), I now do the following:
func viewDidLoad() {
self.view.addSubview(firstSubview)
self.view.addSubview(secondSubview)
}
Then I setup each view in viewWillLayoutSubviews
like so:
func viewWillLayoutSubviews() {
self.firstSubview.frame = CGRectMake(x, y, w, h)
self.secondSubview.frame = CGRectMake(x, z, w, h)
}
This works perfectly from what I can see, and I've only ended up here after having issues with sizing, and element order (is it called hierarchy?).
Any advice would be appreciated.
Upvotes: 0
Views: 252
Reputation: 4319
It depends on when you want your layout code to happen.
For basic layouts, you should initialize views and add subviews in viewDidLoad. And for frame changes, it can be viewDidLayoutSubviews, viewWillLayoutSubviews. You can also use viewWillAppear and viewDidAppear when you want to reload some views (such as updating text after dismissing a presented view controller).
Upvotes: 1