Setting UIImageView image affects layout constraints

蓝咒 提交于 2019-12-22 05:26:25

问题


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)

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


回答1:


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)



回答2:


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?




回答3:


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.



来源:https://stackoverflow.com/questions/46675682/setting-uiimageview-image-affects-layout-constraints

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!