设置UIImageView图像会影响布局约束 [英] Setting UIImageView image affects layout constraints

查看:52
本文介绍了设置UIImageView图像会影响布局约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个具有以下约束的简单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图像会影响布局约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆