birdy
birdy

Reputation: 953

UIStackView: add arranged views with the same width

I have UIStackView and want add to this view some arranged views... sometimes one, sometimes two, three... etc. UIStackView has full width. I want arranged views to have the same width with alignment left, so that they do not fill full width of UIStackView.

This is what I have:

enter image description here

This is what I want:

enter image description here

Is it possible to do it somehow or do I need to change width of UIStackVIew depending on how many arranged I added?

My code:

        // creating views
    stackView = {
        let v = UIStackView()
        v.axis = .horizontal
        v.alignment = .center
        v.distribution = .fillEqually
        v.spacing = 5
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()
 if let img = chosenImage {
            let imageView: UIImageView = {
                let l = UIImageView()
                l.translatesAutoresizingMaskIntoConstraints = false
                l.image = img
                return l
            }()
            self.stackView?.addArrangedSubview(imageView)
            imageView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .width, relatedBy: .equal, toItem: imageView, attribute: .height, multiplier: 1, constant: 1))
            imageView.setNeedsUpdateConstraints()
        } else {
            print("Something went wrong")
        }

Upvotes: 5

Views: 9123

Answers (2)

Trần Thị Diệu My
Trần Thị Diệu My

Reputation: 1423

on storyboard, Select stackview, Attributes inspector -> Stackview -> Distribution, select Fill Equally.

enter image description here

Upvotes: 8

Michał Kwiecień
Michał Kwiecień

Reputation: 2874

You can add an empty clear view to your StackView at the end and set the hugging and resistance priority for this View. It should resize to available space so hugging priority of "fill view" has to be higher and resistance for "fill view" should be low, on your real items set resistance to higher values

enter image description here

Upvotes: 3

Related Questions