Setting UIImageView image affects layout constrain

2019-05-06 18:10发布

I am creation a simple UIImageView with the following constraints:

self.view.addConstraint(imageView.topAnchor.constraint(equalTo: contentLayoutGuide.topAnchor))
self.view.addConstraint(imageView.centerXAnchor.constraint(equalTo: contentLayoutGuide.centerXAnchor))
self.view.addConstraint(imageView.heightAnchor.constraint(equalTo: contentLayoutGuide.heightAnchor))
self.view.addConstraint(imageView.widthAnchor.constraint(equalTo: contentLayoutGuide.heightAnchor))

The important one is the last one, which sets the width equal to the height of the image view and the height of the image view is being defined by top and bottom anchor.

Now this looks perfectly fine (see image below) example image view

However when setting imageView.image the image is all over the screen and way too big. This debugging process fixes it:

po for cn in self.imageView!.constraints { cn.isActive = false }
po CATransaction.flush()

This makes the image fit inside the imageView as it is intended but up until this point, the imageView is messed up.

What is interesting, before setting the image, the imageView itself does not have any constraints and then setting the image creates those two:

- 0 : <NSContentSizeLayoutConstraint:0x6040002b2120 UIImageView:0x7fa98f757b90.width == 488 Hug:250 CompressionResistance:750   (active)>
- 1 : <NSContentSizeLayoutConstraint:0x6040002b2180 UIImageView:0x7fa98f757b90.height == 487 Hug:250 CompressionResistance:750   (active)>

Those constraints seem to break it, because disabling them fixes the problem. They are only added when setting an image

3条回答
时光不老,我们不散
2楼-- · 2019-05-06 19:02

try to set clipsToBounds property to true for UIImageView and check, since for few contentMode options the image goes out of bound of image view if the bounds are not enough to fill the content.

查看更多
聊天终结者
3楼-- · 2019-05-06 19:04

Try to lower the content compression/hugging. I think (correct me if I am wrong) the UIImageView has by default a higher compression/hugging resistance than a UIView (251 to 250). You could try the code below:

    someImage.setContentHuggingPriority(UILayoutPriority(rawValue: 249), for: .horizontal)
    someImage.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 249), for: .horizontal)
    someImage.setContentHuggingPriority(UILayoutPriority(rawValue: 249), for: .vertical)
    someImage.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 249), for: .vertical)
查看更多
啃猪蹄的小仙女
4楼-- · 2019-05-06 19:08

Is your UIImageView masking to bounds? If the image is bigger than the UIImageView then by default it will extend past the bounds

imageView.layer.masksToBounds = true

Alternatively have you tried changing the content fit of the UIImageView to Aspect Fit for example?

查看更多
登录 后发表回答