我创建了一个简单的UI
ImageView,具有以下约束:
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))
重要的一个是最后一个,它将宽度设置为等于图像视图的高度,图像视图的高度由顶部和底部锚定义.
但是,在设置imageView.image时,图像遍布整个屏幕并且太大了.
此调试过程修复了它:
po for cn in self.imageView!.constraints { cn.isActive = false } po CATransaction.flush()
这使得图像适合imageView内部,但直到此时,imageView才搞砸了.
有趣的是,在设置图像之前,imageView本身没有任何约束,然后设置图像会创建这两个:
- 0 : <NSContentSizeLayoutConstraint:0x6040002b2120 UIImageView:0x7fa98f757b90.width == 488 Hug:250 CompressionResistance:750 (active)> - 1 : <NSContentSizeLayoutConstraint:0x6040002b2180 UIImageView:0x7fa98f757b90.height == 487 Hug:250 CompressionResistance:750 (active)>
解决方法
尝试降低内容压缩/拥抱.我认为(纠正我,如果我错了)UIImageView默认具有比UIView(251到250)更高的压缩/拥抱阻力.您可以尝试以下代码:
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)