iOS:使用定位以编程方式将UIImageView与底部对齐
我试图以编程方式创建一个iOS:使用定位以编程方式将UIImageView与底部对齐,ios,swift,uiimageview,uikit,constraints,Ios,Swift,Uiimageview,Uikit,Constraints,我试图以编程方式创建一个UIImageView(因此没有故事板/UI编辑器),并使用锚定约束将其对齐。 UIImageView应与底部对齐并缩放以适应底部区域(如全宽页脚),但应保持纵横比,有点像故事板编辑器中的可用内容? viewdiload()中的当前代码如下所示,但无论我做什么,图像都显示在顶部,似乎ImageView(而不是图像)占据了父视图的整个高度 // Create and add image view let imgView = UIImageView(image : UIIm
UIImageView
(因此没有故事板/UI编辑器),并使用锚定约束将其对齐。
UIImageView应与底部对齐并缩放以适应底部区域(如全宽页脚),但应保持纵横比,有点像故事板编辑器中的可用内容?
viewdiload()
中的当前代码如下所示,但无论我做什么,图像都显示在顶部,似乎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),
])
我能够利用上面的评论和进一步的实验,通过计算和设置图像比率中的高度锚来找到解决方案
// 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)
])
我能够利用上面的评论和进一步的实验,通过计算和设置图像比率中的高度锚来找到解决方案
// 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)
])
不幸的是,这给出了同样的结果。我尝试将所有代码移动到
viewDidLayoutSubviews()
,只移动约束部分尝试将heightAchor
赋予imageView
@KishanBhatiya,你能建议我应该为heightAnchor
编写什么样的约束/代码吗?添加imgView.heightAnchor.constraint(equalToConstant:50)NSLayoutConstraint中的
。激活
@KishanBhatiya好的,似乎有效果。问题是我不能输入50,因为这取决于图像的屏幕大小/纵横比。我需要的图像是全宽度不幸的是,这会给出相同的结果。我尝试将所有代码移动到viewDidLayoutSubviews()
,只移动约束部分尝试将heightAchor
赋予imageView
@KishanBhatiya,你能建议我应该为heightAnchor
编写什么样的约束/代码吗?添加imgView.heightAnchor.constraint(equalToConstant:50)NSLayoutConstraint中的
。激活
@KishanBhatiya好的,似乎有效果。问题是我不能输入50,因为这取决于图像的屏幕大小/纵横比。我需要的图像是全宽