5

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")
        }
birdy
  • 943
  • 13
  • 25
  • How do you specify what width the views should be? Is it a fixed value? – Upholder Of Truth Jun 09 '17 at 12:47
  • @UpholderOfTruth I've added the code sample to my question. – birdy Jun 09 '17 at 14:41
  • That's not going to work. You have set the stack view so that it's arranged views fill it equally with a 5pt spacing. Then for the image you have set the height equal to the width + 1pt. So the width will be determined by dividing up the width of the stack view and then the height adjusted accordingly. I think the best approach has already been added with the extra clear view and content hugging and resistance. – Upholder Of Truth Jun 09 '17 at 15:04

2 Answers2

7

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

enter image description here

3

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

Michał Kwiecień
  • 2,734
  • 1
  • 20
  • 23