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

2

5

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

Swithin answered 19/10, 2015 at 17:0 Comment(0)
L
14

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.

Lumisterol answered 19/10, 2015 at 17:35 Comment(2)
If i could give you +2 I would, trust me :) Thank you this solved my problem.Thinia
can we do this without using stackview ?Tetrabasic
N
-2

There's no visibility setting. But you can just set the alpha to 0

Nonsmoker answered 1/5, 2016 at 0:45 Comment(1)
This does not claim the space, it will still take up spaceKnighthead

© 2022 - 2024 — McMap. All rights reserved.