简体   繁体   English

UIImageView 忽略 UIStackView 中的 widthAnchor

[英]UIImageView ignores widthAnchor inside UIStackView

I'm trying to align and scale an image inside a 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)
        ])
    }
    
}

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?问题:为什么 UIImageView 忽略了我 50pt 的 widthAnchor 约束,为什么原始图像的纵横比会改变? How can I constrain the UIImage (or the UIImageView) to eg half the screen width and maintain the aspect ratio?如何将 UIImage(或 UIImageView)限制为例如屏幕宽度的一半保持纵横比?

By default, a vertical stack view has .alignment =.fill ... so it will stretch the arranged subviews to "fill the width of the stack view."默认情况下,垂直堆栈视图具有.alignment =.fill ... 因此它将拉伸排列的子视图以“填充堆栈视图的宽度”。

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.作为旁注,摆脱stackView.distribution =.fillProportionally ......它几乎肯定不是你想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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