Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
//...
like image 225
Jerem Lachkar Avatar asked Jan 01 '23 03:01

Jerem Lachkar


2 Answers

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)
    }
}
like image 181
Jerem Lachkar Avatar answered Jan 03 '23 16:01

Jerem Lachkar


What you could do is set a custom spacing between the second and third element.

myStackView.setCustomSpacing(30.0, after: my2ndElementLabel)
like image 31
Rool Paap Avatar answered Jan 03 '23 16:01

Rool Paap