UICollection View 自动布局约束正在被打破

UICollection View Auto-layout Constraints Are Breaking

我有一个 ViewController,里面有一个 UICollectionView。在情节提要中,我已经布置了单元格。

我添加的单元格:

然后我在故事板中添加了自动布局约束:

当我 运行 模拟器时,这不起作用。我认为它不起作用,因为我使用的是自定义单元格。因此,我通过为所有约束设置 IBOutlets 并在 cellForItemAtIndexPath 方法中重置它们的值来修复它并将其正确设置为 运行:

    //Layout cell
    cell.img_Height.constant = 50
    cell.img_Width.constant = 50
    cell.leading_Img_to_Container.constant = 10
    cell.trailing_Img_to_Container.constant = 10
    cell.top_Img_to_Container.constant = 10
    cell.bottom_Img_to_Container.constant = 10

    cell.top_Container_to_Cell.constant = 10
    cell.bottom_Container_to_Label.constant = 0
    cell.horizontalCenter_Container_to_Cell.constant = 0

    cell.bottom_Label_to_Cell.constant = 0 //Flexible constraint: In storyboard this relation is 'Greater than or equal to'
    cell.horizontalCenter_Container_to_Label.constant = 0

当我 运行 应用程序时,集合视图看起来不错。然而,当我检查控制台时,它说它正在打破约束:

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. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) ( "", "", "", "", "", "= UILabel:0x7fc0026d2580'Grocery List'.bottom>", "" ) Will attempt to recover by breaking constraint NSLayoutConstraint:0x7fc0026ba9d0 V:[UIImageView:0x7fc0026d2440(50)]>

我一直在调整约束并尝试对此进行调试,但我无法弄清楚我做错了什么。如何正确设置布局?

cell.img_Height.constant = 50
cell.img_Width.constant = 50
cell.leading_Img_to_Container.constant = 10
cell.trailing_Img_to_Container.constant = 10
cell.top_Img_to_Container.constant = 10
cell.bottom_Img_to_Container.constant = 10

您对 cell.img 添加了过多的约束。
top_Img_toContainer 和底部 img_to_Container 约束是不必要的。

有一个原则你需要知道。

您添加到情节提要中的每个视图都必须有足够的约束(不多也不少)以确认它是:

宽度

身高

X位置

Y位置

我能够通过删除我的图像所在的容器来解决我的问题,这简化了布局,因此也简化了所需的约束。

由于单元格是预先确定的大小,我的新方法只是将事物居中并确保它们的 y 位置相对于彼此是清晰的。

此时,我的约束:

  • 使用大于 0 ( >=0 ) 指示到单元格边缘的距离,并且具有低优先级,因为效果应该发生,因为它们居中。
  • 我的最高优先级约束确保单元格内的视图之间存在正确数量的 space。