我在我的 iOS 应用程序中使用SnapKit进行自动布局。
我需要在屏幕的最顶部显示一个图像视图。它将具有动态高度和宽度的图像。我需要它的顶部边缘与视图的顶部对齐。我需要它水平居中。我需要它与屏幕的左右边距大于或等于 10。我需要它的高度根据内容动态变化,最大高度等于 300。我需要它保持其纵横比并根据需要使用自动布局自动减小其宽度或高度。
我认为下面的代码应该可以完成这个工作:
let padding = 10.0
let preview = UIImageView()
preview.setContentHuggingPriority(.required, for: .vertical)
preview.setContentHuggingPriority(.required, for: .horizontal)
preview.backgroundColor = .red
preview.contentMode = .scaleAspectFit
let image = UIImage(named: "demo3")!
preview.image = image
preview.clipsToBounds = true
view.addSubview(preview)
preview.snp.makeConstraints { make in
make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
make.centerX.equalToSuperview()
make.left.right.greaterThanOrEqualToSuperview().inset(padding).priority(.required)
make.height.lessThanOrEqualTo(300).priority(.required)
make.width.equalTo(preview.snp.height).multipliedBy(image.size.width / image.size.height).priority(.required)
}
这对于横向图像(宽度大于高度)似乎工作正常,但它在纵向图像中不起作用:
适用于风景图像:
肖像图像失败。请注意高度不再是lessThanOrEqualTo(300)
:
这是因为 Xcode 打印了一条警告,称它无法满足约束,因此必须打破高度约束:
Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
(
"<SnapKit.LayoutConstraint:[email protected]#54 UIImageView:0x7f81b19101e0.centerX == UIView:0x7f81b183dc30.centerX>",
"<SnapKit.LayoutConstraint:[email protected]#55 UIImageView:0x7f81b19101e0.right >= UIView:0x7f81b183dc30.right - 12.0>",
"<SnapKit.LayoutConstraint:[email protected]#56 UIImageView:0x7f81b19101e0.height <= 300.0>",
"<SnapKit.LayoutConstraint:[email protected]#57 UIImageView:0x7f81b19101e0.width == UIImageView:0x7f81b19101e0.height * 0.666748046875>",
"<NSLayoutConstraint:0x600003e37a20 'UIView-Encapsulated-Layout-Width' UIView:0x7f81b183dc30.width == 430 (active)>"
)
Will attempt to recover by breaking constraint
<SnapKit.LayoutConstraint:[email protected]#56 UIImageView:0x7f81b19101e0.height <= 300.0>
我原本期望它能减小宽度并保持纵横比以满足条件。但它没有这样做。
我认为你需要的是更换
和
对我来说它现在运行得很好!