问题描述
我正在创建一个具有以下约束的简单 UIImageView:
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)
但是,当设置 imageView.image
时,图像会遍布整个屏幕并且太大了.这个调试过程修复了它:
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()
这使得图像按预期适合 imageView,但直到此时,imageView 都被弄乱了.
This makes the image fit inside the imageView as it is intended but up until this point, the imageView is messed up.
有趣的是,在设置图像之前,imageView 本身没有任何约束,然后设置图像会创建这两个:
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
推荐答案
尽量降低内容压缩/拥抱.我认为(如果我错了,请纠正我)默认情况下 UIImageView 比 UIView 具有更高的压缩/拥抱阻力(251 到 250).你可以试试下面的代码:
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)
这篇关于设置 UIImageView 图像会影响布局约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!