Manuel
Manuel

Reputation: 15082

Swift: How to get the size of a subview before it is being displayed?

A view (a) contains a subview (b) which contains a text label.

The text label's text is set in viewDidLoad of view (a). The amount of text in the label changes the size of subview (b).

I get the correct size of subview (b) only in viewDidAppear of view (a), but not in viewDidLayoutSubviews.

How to get the size of the subview (b) in the view controller of view (a) before it is displayed?

Update: Using auto-layout

Upvotes: 2

Views: 2365

Answers (1)

Manuel
Manuel

Reputation: 15082

The problem was that I was calling layoutIfNeeded during viewDidLoad and before the text label's text was set.

It forced the viewDidLayoutSubviews to be called immediately and not anymore thereafter.

Here is the bad sequence of calls including the subview's frame height which is 163.0 with an empty text label on the storyboard and 190.5 with the text label's text set.

viewDidLoad begin: frame.height: 163.0
viewDidLayoutSubviews: frame.height: 161.5 // should not be called yet
viewDidLoad end: frame.height: 161.5
viewWillAppear: frame.height: 161.5
viewDidAppear: frame.height: 190.5

After removing layoutIfNeeded:

viewDidLoad begin: frame.height: 163.0
viewDidLoad end: frame.height: 163.0
viewWillAppear: frame.height: 163.0
viewDidLayoutSubviews: frame.height: 190.5
viewDidAppear: frame.height: 190.5

Upvotes: 5

Related Questions