与其尝试在图像视图中左对齐图像,不如以编程方式向图像视图添加宽度约束,以便没有“多余空间”。
假设您有一个UIImageView
带有“Aspect Fit”的内容模式,并且在界面构建器中添加了一个固定的高度约束。然后,在相关的视图控制器中,检查图像的纵横比并应用必要的宽度约束以将图像视图捕捉到包含的图像。例如:
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// UIImage loaded from somewhere...
imageView.image = uiImage
// Check the UIImageView for existing height constraints
let heightConstraints = imageView.constraints.filter{$0.firstAttribute == .height}
if let imageViewHeight = heightConstraints.first?.constant {
// Calculate the width which would make the image view fit
// the image perfectly, and constrain the view to that width.
let desiredImageViewWidth = (imageViewHeight / uiImage.size.height) * uiImage.size.width
imageView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: desiredImageViewWidth))
}
}
要将其应用于您的问题,您可以将两个UIImageView
s 约束为彼此相邻,为两者设置一个固定的高度约束(具有相同的值),然后使用上述代码以编程方式设置宽度。