当将contentMode设置为UIViewContentModeScaleAspectFit时,如何将UIImageView对齐到左侧或右侧?

27
我想在使用UIImageViewUIViewContentModeScaleAspectFit时控制图像对齐方式。
例如,我有两个UIImageView在一个视图中(如上图),它们的contentMode都是UIViewContentModeScaleAspectFit。现在我想将图像3设置为右对齐,将图像4设置为左对齐,这样这两个图像就可以放在一起了。
我尝试将contentMode设置为UIViewContentModeScaleAspect|UIViewContentModeLeft,但结果更糟糕了。
欢迎提出任何建议。
3个回答

38

终于,我找到了可以解决这个问题的 UIImageViewAligned 项目。

感谢 @Marchy,还有 Swift 版本的 UIImageViewAlignedSwift

请注意,某些约束需要进行编辑,否则图片可能无法显示。

例如,"lessThanOrEqual" 约束应该改为 "equal"。


6
这里有一个用Swift重写的版本:https://github.com/sochalewski/UIImageViewAlignedSwift - Marchy
@Marchy 非常感谢您的快速版本。它对我很有帮助。我认为您应该将其作为单独的答案发布,因为有些人可能会错过评论。 - viral
这个库的Swift实现:imageView.contentMode = .scaleAspectFit imageView.setValue("true", forKeyPath: "alignTop") - Deepansh Jagga
两个库都显示非常小的图像,它们似乎在约束之前应用。 - Top-Master

9

不要试图在图像视图中左对齐图像,您可以通过编程方式向图像视图添加宽度约束,以便没有“多余空间”。

假设您有一个使用“Aspect Fit”内容模式和在接口构建器中添加了固定高度约束的UIImageView。然后,在相关的视图控制器中,检查图像的纵横比,并应用必要的宽度约束来捕捉图像视图到包含的图像。例如:

@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 约束在一起,设置相同的固定高度约束,并使用上述代码以编程方式设置宽度。


5

对于一些人来说,另一个选项可能是调整 UIImageView 上的 Content Hugging Priority。在 Interface Builder 中添加一个低优先级的约束到 UIImageView

enter image description here

在添加图片之前,这将满足约束条件。然后将UIImageView的Content Hugging Priority设置为宽度的高值(如果您是顶部/底部对齐,则为高度)。

enter image description here

然后只需将UIImageView的Content Mode设置为所需模式即可。希望这可以帮到你!

那对我来说实际上起作用了,只需要做一些小调整! - Aly Yakan
在我看来,这是正确的答案。设置一个低优先级的连接约束,然后提高内容紧贴优先级。像魔术一样有效。 - Hubert Kunnemeyer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接