0
votes

I'm trying to align and scale an image inside a UIStackView:

class LogoLine: UIViewController {  
    override func viewDidLoad() {
        let label = UILabel()
        label.text = "powered by"
        label.textColor = .label
        label.textAlignment = .center
        
        let logoToUse = UIImage(named: "Image")
        let imageView = UIImageView(image: logoToUse!)
        
        let stackView = UIStackView(arrangedSubviews: [label, imageView])
        stackView.axis = .vertical
        stackView.distribution = .fillProportionally

        view.addSubview(stackView)
        
        stackView.translatesAutoresizingMaskIntoConstraints = false

        NSLayoutConstraint.activate([
            imageView.widthAnchor.constraint(equalToConstant: 50), // this gets ignored
            stackView.topAnchor.constraint(equalTo: self.view.topAnchor),
            stackView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
            stackView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
            view.heightAnchor.constraint(equalTo: stackView.heightAnchor)
        ])
    }
    
}

This is how it looks in the simulator (going from border to border):

enter image description here

Question: Why is the UIImageView ignoring my widthAnchor constraint of 50pt, and why does the aspect ratio of the original image get changed? How can I constrain the UIImage (or the UIImageView) to e.g. half the screen width and maintain the aspect ratio?

1
Set imageView.contentMode = .aspectFit.Pranav Kasetti

1 Answers

2
votes

By default, a vertical stack view has .alignment = .fill ... so it will stretch the arranged subviews to "fill the width of the stack view."

Change it to:

stackView.alignment = .center

As a side note, get rid of the stackView.distribution = .fillProportionally ... it almost certainly is not what you want.