iOS:使用锚点以编程方式将UIImageView对齐到底部

问题描述 投票:0回答:1

我正在尝试以编程方式创建UIImageView(因此没有情节提要/ UI编辑器),并使用锚点约束对其进行对齐。UIImageView应该与底部对齐并缩放以适合底部区域(例如全角页脚),但是要保持宽高比,就像情节提要板编辑器中有什么可用?

enter image description here

我在viewDidLoad()中的当前代码看起来像这样,但是无论我做什么,图像都显示在顶部,并且似乎ImageView(而不是图像)占据了父视图的整个高度。

// Create and add image view
let imgView = UIImageView(image : UIImage(named : "Images/main_bottom.png"))
imgView.translatesAutoresizingMaskIntoConstraints = false
imgView.contentMode = .scaleAspectFit

view.addSubview(imgView)


// Align image view
let margins = view.safeAreaLayoutGuide

NSLayoutConstraint.activate([
    imgView.leadingAnchor.constraint(equalTo: margins.leadingAnchor),
    imgView.trailingAnchor.constraint(equalTo: margins.trailingAnchor),
    imgView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])

我正在尝试以编程方式创建UIImageView(因此没有情节提要/ UI编辑器,并使用锚点约束对其进行对齐。 UIImageView应该与底部对齐并缩放以适合...

ios swift uiimageview uikit constraints
1个回答
0
投票

我能够通过上面的评论和进一步的实验,通过从图像比率计算和设置高度锚点找到解决方案。

// Compute image ratio
let ratio = imgView.intrinsicContentSize.height / imgView.intrinsicContentSize.width

// Set height anchor as a computed value of the (auto-scaled) width, and the image ratio
NSLayoutConstraint.activate([
   // ...other contraints go here still...
   imgView.heightAnchor.constraint(equalTo: imgView.widthAnchor, multiplier: ratio)
])
© www.soinside.com 2019 - 2024. All rights reserved.