UIImageView 忽略 UIStackView 内的 widthAnchor

UIImageView ignores widthAnchor inside UIStackView

我正在尝试对齐和缩放 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)
        ])
    }
    
}

这是它在模拟器中的样子(从边界到边界):

问题:为什么UIImageView忽略了我的50pt的widthAnchor约束,为什么原图的宽高比变了?如何将 UIImage(或 UIImageView)限制为例如屏幕宽度的一半 保持纵横比?

默认情况下,垂直堆栈视图有 .alignment = .fill ...所以它会拉伸排列的子视图以“填充堆栈视图的宽度”。

改为:

stackView.alignment = .center

作为旁注,去掉 stackView.distribution = .fillProportionally ... 几乎可以肯定 不是你想要的.