IOSAUTOLAYOUT-无法使高度较小。

问题描述 投票:0回答:1
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) }

对于景观图像(宽度长于高度),这似乎可以很好地工作,但它在肖像图像中破裂:


景观图像中的工作:


enter image description here




肖像图像中的模仿。注意高度不再是
lessThanOrEqualTo(300)

这是由于Xcode打印的警告,该警告说它无法满足约束,并且必须打破高度约束: enter image description hereUnable 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> 我本来可以预期它会减小其宽度,同时保持纵横比满足条件。但事实并非如此。

我认为您在这里需要什么是替换
make.left.right.greaterThanOrEqualToSuperview().inset(padding).priority(.required)

make.left.greaterThanOrEqualToSuperview().inset(padding) make.right.lessThanOrEqualToSuperview().inset(padding)
ios swift autolayout nslayoutconstraint
1个回答
0
投票
对于我来说,它现在很好!

landscape

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.