Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Swift - How to hide a UIView element and claim the space?

I'm new to iOS coming from Android background.

When applying .hidden = true to a UIView, it is hidden however it still takes its space. Is there a way to claim this space when the view is gone (similar to setVisibility(View.GONE) in Android?

Thanks

like image 657
Golan Shay Avatar asked Dec 24 '22 13:12

Golan Shay


1 Answers

If you are targeting iOS 9 or later, you can use a UIStackView to accomplish this automatically (similar to LinearLayout on Android). When you set a view that is contained in a UIStackView to hidden, the remaining views will shift to reclaim the space.

You can animate the shift by setting view.hidden = true inside of an animation block by using

UIView.animateWithDuration(_:delay:options:animations:completion:)

or the like.

If you are targeting iOS versions lower than 9 (where UIStackView is not supported), you have to manually update your auto layout constraints whenever you hide or show the view.

For example, say you have 3 views stacked on top of each other, called view1, view2, and view3, you first remove view2 and view3's top constraints by calling

view2TopConstraint.active = false
view3TopConstraint.active = false

and then add a top constraint on view3 that is pinned to the bottom of view1

let newView2TopConstraint = NSLayoutConstraint(item: view3, attribute: .Top, relatedBy: .Equal, toItem: view1, attribute: .Bottom, multiplier: 1.0, constant: 0.0)
newView2TopConstraint.active = true

There are many ways to achieve this. This is just one example.

like image 156
tcarey Avatar answered Dec 31 '22 12:12

tcarey