Bnj Bnj - 10 months ago 72
Swift Question

UIStackView Distribution Fill Equally

So, I have a

that contains four (4)
s. If I remove one (1) of those
s, the other three (3) will fill the entire space in the UIStackView.


How can I add a max height on a
so that it will now fill the entire space of the
even the distribution is filled equally? I read something about adding a constraint but I'm not able to make it work. I'm using swift by the way.

Thank you.

Answer Source

If I'm not mistaking, what are you facing is:

enter image description here

And what are you asking for is:

enter image description here

Well, if that's your case -and I hope it is-, I achieved this by doing a pretty simple trick:

P.S: I assume that you added the right constraints for your stackView.

If your stackView doesn't has an "Equal Height" constraint, add one:

enter image description here

Now, add it as an IBOutlet to the assigned ViewController, in my example I'm calling it stackHeight:

@IBOutlet weak var stackHeight: NSLayoutConstraint!

On the event that you want to hide the view -in my example, I'm hiding the orange button besed on IBAction assinged to itself, when tapping on it, should be hidden- you need to get the height of the view that you want to hide and subtract from stackHeight.constant:

    @IBAction func orangeTapped(_ sender: AnyObject) {
        orange.isHidden = true

        // here we go:
        stackHeight.constant = stackHeight.constant - orange.frame.size.height

Hope this helps.