UITableViewCell 图像全尺寸与正确的纵横比

UITableViewCell Image full-size with right aspect ratio

我创建了一个tableviewcell。在它是一个图像。我想在列的整个宽度上显示图像。 为此,我添加了所有设置为零的约束: -领先space - 尾随 space - 顶部 space - 底部 space 我还定义了纵横比约束 8:6 以获得图像的正确纵横比。

在 Interface Builder 中,我得到 "red arrow" 错误 "Need constraints for: X position of width"。

当我 运行 代码(它是可编译的)时,它显示得很好。但是我收到 运行时间限制警告:

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. 
(
    "<NSLayoutConstraint:0x60800008cfd0 UILayoutGuide:0x6080001a5080'UIViewSafeAreaLayoutGuide'.bottom == UIImageView:0x7fc9fa90fa10.bottom + 8   (active)>",
    "<NSLayoutConstraint:0x60800008d2a0 UIImageView:0x7fc9fa90fa10.centerY == UILayoutGuide:0x6080001a5080'UIViewSafeAreaLayoutGuide'.centerY   (active)>",
    "<NSLayoutConstraint:0x60800008d2f0 UIImageView:0x7fc9fa90fa10.top == UILayoutGuide:0x6080001a5080'UIViewSafeAreaLayoutGuide'.top + 7   (active)>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x60800008d2a0 UIImageView:0x7fc9fa90fa10.centerY == UILayoutGuide:0x6080001a5080'UIViewSafeAreaLayoutGuide'.centerY   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.

我看不出我做错了什么,有人能给我指出正确的方向吗?

问题是,只要您的像元大小不具有 8:6 的比率,您的约束就会发生冲突。

有多种方法可以解决此问题,但我认为最简单的方法是将 leadingtrailing 约束替换为 center horizontally 约束。图像现在将居中,其高度由单元格的高度设置,宽度由宽高比约束设置。唯一需要注意的是,如果单元格变得比 8:6 窄,在这种情况下,图像将延伸到 left/right 边缘之外。