代码之家  ›  专栏  ›  技术社区  ›  sudoExclamationExclamation

iOS自动布局-高度不能小于ThanOrEqualTo

  •  0
  • sudoExclamationExclamation  · 技术社区  · 2 月前

    我正在使用 SnapKit 用于在我的iOS应用程序中自动布局。

    我需要在屏幕的最顶部显示图像视图。它将具有动态高度和宽度的图像。我需要它的顶部边缘与视图的顶部对齐。我需要它水平居中。我需要它与屏幕的左右边距大于或等于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) :

    enter image description here

    这是由于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>
    

    我原本预计它会在保持纵横比以满足条件的同时减小宽度。但事实并非如此。

    1 回复  |  直到 2 月前
        1
  •  1
  •   Kiryl Famin    2 月前

    我想你需要的是更换

    make.left.right.greaterThanOrEqualToSuperview().inset(padding).priority(.required)
    

    具有

    make.left.greaterThanOrEqualToSuperview().inset(padding)
    make.right.lessThanOrEqualToSuperview().inset(padding)
    

    对我来说,它现在运行得很好!

    landscape portrait