如何在 Interface Builder 中实现这种布局?

How to achieve this layout in Interface Builder?

我正在使用静态 Table 视图控制器并在 Interface Builder 中定义 UI。

我希望所有 UI 标签的宽度相同,以便 UITextFields 的左侧对齐。

如果我强制设置一个宽度,那么他们经常互相透支。

我正在考虑根据控制器内 "Safe Message" 的宽度以编程方式修改 UI 标签宽度,但我无法重新布局。

let width = labelSafeMessage.frame.size.width;
labelName.frame.size.width = labelSafeMessage.frame.size.width;
labelName.sizeToFit();
labelMessage.frame.size.width = labelSafeMessage.frame.size.width;
labelMessage.sizeToFit();

可以通过在tableView显示数据之前计算宽度来避免重新布局

得到集合中最大的字符串,然后用这个

var str = "Hello, playground"
let constraintRect = CGSize(width: CGFloat.greatestFiniteMagnitude, height: DEFINED_HEIGHT)
let boundingBox = (str as? NSString)?.boundingRect(with: constraintRect, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: FONT], context: nil)
boundingBox.width //width for the labels

只需将 DEFINED_HEIGHT 替换为标签的高度,即行的高度减去容纳它的顶部和底部约束。 和 FONT,用于标签中使用的字体。

您可以只使用 Interface Build 来做到这一点,您不需要强制标签具有相同的 size.The 您唯一需要做的就是将 UITextFields 的前导间距设置为 superview,它们将对齐到左边。

您可以使用包含 UIViews.

的垂直 UIStackView 而不是使用 UITableView

将您的 UILabels 约束设置为 Align Leading edgesAlign Trailing edges 并设置 Content Hugging PriorityContent Compression Resistance Priority 以及标签不被裁剪和合身。

UITextFields 约束设置为 Align Leading edgesAlign Trailing edges 彼此,这样就可以了。