How to programmatically determine the height of UIStackView after a subview has been hidden swift
Asked Answered
M

1

9

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?

Maugre answered 4/4, 2018 at 2:18 Comment(1)
viewDidLoad is too soon. Try viewDidAppear.Theatrics
E
24

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.

Earreach answered 4/4, 2018 at 2:23 Comment(6)
Thanks for the answer, I still receive the old height after .layoutIfNeeded().Maugre
@Maugre Have you tried removing the arranged subview altogether (not just hiding it) to see if that changes the height?Earreach
I changed it just now from hiding to .removeFromSuperview(), still no change in height?Maugre
@Maugre you need to call setNeedsLayout() before .layoutIfNeeded(), then get the frame height.Sorilda
@Maugre instead of removeFromSuperview() try stackview.removeArrangedSubview(subview1)Cons
This solution doesn't work for me either.Gilmer

© 2022 - 2024 — McMap. All rights reserved.