Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")
        }
like image 979
birdy Avatar asked Jun 09 '17 12:06

birdy


2 Answers

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

enter image description here

like image 144
Trần Thị Diệu My Avatar answered Sep 27 '22 23:09

Trần Thị Diệu My


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

like image 39
Michał Kwiecień Avatar answered Sep 28 '22 00:09

Michał Kwiecień