简体   繁体   中英

UIImageView ignores widthAnchor inside UIStackView

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):

在此处输入图像描述

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 eg half the screen width and maintain the aspect ratio?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM