首页 > 解决方案 > 根据拾取的图像(来自图像选择器)框架更改图像视图框架 SWIFT

问题描述

我有一个图像视图,其中有一个设置的框架,但是当用户单击它并更改图像(UIImagePickerController)时,我不知何故需要图像视图的框架更改为图像的框架。

当他们单击图像的选择按钮时,这就是我运行的代码。

itemImage.contentMode = .scaleAspectFit
self.itemImage.image = pickedImage as? UIImage

所以图像出现在图像视图中,但我需要一些帮助来找到一种方法来让图像视图框架更改为拾取的图像框架。

这就是我所说的框架不变的意思。

框架不变

谢谢

标签: swiftimageimageviewframes

解决方案


在我看来,您的 imageView 已经应用了一些约束。我建议对其应用大小限制。

// declare these at the top of the file so that the constraints can be removed when new images are selected
private var widthConstraint: NSLayoutConstraint?
private var heightConstraint: NSLayoutConstraint?

// remove old constraint
widthConstraint?.isActive = false
// fix the imageview width to that of the picked image
widthConstraint = itemImage.widthAnchor.constraint(equalToConstant: pickedImage.size.width)
widthConstraint?.isActive = true

heightConstraint?.isActive = false
heightConstraint = itemImage.heightAnchor.constraint(equalToConstant: pickedImage.size.height)
heightConstraint?.isActive = true

推荐阅读