how to set the UIImageView align left or right whe

2019-04-03 22:35发布

I want to control the image alignment when using the UIViewContentModeScaleAspectFit in UIImageView.

enter image description here

For example, I have two UIImageView in one view as above.these two UIImageView's contentMode is UIViewContentModeScaleAspectFit. Now I want to set image 3 to align right and image 4 to align left, so that these two images can be together.

I try to set the contentMode to UIViewContentModeScaleAspect|UIViewContentModeLeft, but it make things worse.

Any suggestions are appreciated.

3条回答
戒情不戒烟
2楼-- · 2019-04-03 23:04

Rather than trying to left align the image within the image view, you could programatically add a width constraint to the image view so that there is no "excess space".

Suppose you have a UIImageView with "Aspect Fit" content mode, and a fixed height constraint added in the interface builder. Then, in the relevant view controller, check the aspect ratio of the image and apply the necessary width constraint to snap the image view to the contained image. E.g.:

@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))
    }
}

To apply this to your problem, you could constrain your two UIImageViews to be next to one another, set a fixed height constraint for both (of the same value), and then programatically set the width using the above code.

查看更多
等我变得足够好
3楼-- · 2019-04-03 23:09

Finally, I find UIImageViewAligned project which can work it out.

Thanks to @Marchy, there is also swift version UIImageViewAlignedSwift

查看更多
啃猪蹄的小仙女
4楼-- · 2019-04-03 23:18

Another option for some people might be to adjust the Content Hugging Priority on the UIImageView. In Interface Builder add a constraint to the UIImageView with a low priority.

enter image description here

This will satisfy the constraints until an image is added. Then set the UIImageView's Content Hugging Priority to a high value for width (or height if you are top/bottom aligning).

enter image description here

Then just set the UIImageView's Content Mode to what you want. Hope this helps!

查看更多
登录 后发表回答