7

I am using a UIStackView within a UIScrollView and I want to determine the height of the stack view so I can programmatically adjust the height of the scrollview to accomodate when subviews are hidden.

I am using

stackView.frame.height 

to determine stack view height. This is called in viewDidLoad() but it is always the same height value from the storyboard no matter if subviews are hidden or not.

How do I determine height?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Khoury
  • 411
  • 1
  • 4
  • 21

1 Answers1

23

After making layout changes to any view, it has to recalculate it's frame after the function is completed. To get the updated frame right away, call:

stackView.layoutIfNeeded()

Example:

print(stackView.frame.height) // old height
subview1.isHidden = true
print(stackView.frame.height) // still old height
stackView.layoutIfNeeded()
print(stackView.frame.height) // new height

See the documentation for more details.

tktsubota
  • 9,371
  • 3
  • 32
  • 40