swiftuistackviewlayoutmargins

Add layoutMargins to one element in a UIStackView


I would like to create a vertical stackview with 3 elements in it. I want a bit more space only between the 2nd and the last element. So I thought about adding to the last element :

mylastelement.layoutMargins = UIEdgeInsets(top:30, left:0,bottom:0, right:0)

But the layoutmargins are not applied in my stackview. Is there any easy way to achieve that (Id like to avoid to modify the last element inner height).

EDIT : I just tried to increase 2nd element height (+50) within its frame by doing :

my2ndElementLabel.sizeToFit()
my2ndElementLabel.frame = CGRect(x:my2ndElementLabel.frame.origin.x,y:lmy2ndElementLabel.frame.origin.y,
                                 width:my2ndElementLabel.frame.width, height:my2ndElementLabel.frame.height + 50)

but it has no effect.

EDIT2 : I tried to add a random view to my UIStackView, but the the view is just ignored ! May have missed something in understanding how UIKit work ?... :

let v = UIView(frame:CGRect(x:0,y:0,width:100,height:400))
v.backgroundColor = .red
myStackView.addArrangedSubview(v)
//...

Solution

  • Here is an extension I made that helps to achieve fast such margins :

    extension UIStackView {
    
        func addArrangedSubview(_ v:UIView, withMargin m:UIEdgeInsets )
        {
            let containerForMargin = UIView()
            containerForMargin.addSubview(v)
            v.translatesAutoresizingMaskIntoConstraints = false
            NSLayoutConstraint.activate([
                v.topAnchor.constraint(equalTo: containerForMargin.topAnchor, constant:m.top ),
                v.bottomAnchor.constraint(equalTo: containerForMargin.bottomAnchor, constant: m.bottom ),
                v.leftAnchor.constraint(equalTo: containerForMargin.leftAnchor, constant: m.left),
                v.rightAnchor.constraint(equalTo: containerForMargin.rightAnchor, constant: m.right)
            ])
    
            addArrangedSubview(containerForMargin)
        }
    }