UIStackView 和多行标签?

UIStackView and Multiline Labels?

我试图让它工作,但界面构建器正在努力,我想知道是否有人对此有合适的解决方案。

所以我想要一个包含多行标签的堆栈视图。第一次点击 google () 告诉您将标签嵌入视图 (A),然后将该视图拖到另一个视图 (B)(因为嵌入视图 (A) 有一个 20pixel垫)然后取消嵌入第一个视图(A)....瞧。除了这只会欺骗水平堆栈的堆栈视图,如果你继续堆栈视图,你仍然会遇到很多问题(我将在问题的后面用截图来演示)。

我找到了another guide on google that criticizes a potential fix for the problem, fixing the stackviews width. The author makes the point that Apple didn't intend for you to be doing that, after all it's supposed to be auto layout, not fixed layout. This guide theorises that the issue is just a bug and that you can create a stackview with a single line label, set it all up and THEN add the multiple lines. I tried this and it didn't work, it simply messed the entire stack view up! The stack view will warp and essentially break unless the label has number of lines set to 1 and only 1. (Image 1) Stackview with label set to have multiple lines.

所以我之前谈到了在视图中嵌入段落标签。 This doesn't cause any errors in the storyboard,(Image 2) 您无法真正将文本与其他 UIStack 正确对齐,但这不是我要立即解决的问题。什么是问题是在运行时发生了什么...... Simulator, Portrait (Image 3), Simulator, Landscape (Image 4)。

我在实际设备上试过 运行 看看它是否只是一个模拟器错误,但同样的事情发生在我的 iphone 6. 可以肯定地说这可能行不通!

哦,在我们继续之前,我将按以下方式构建堆栈视图:

[name - placeholder]
[phone - placeholder]
[address - placeholder]
, setting a spacing of 8 and equal fill
,vertically stacking all of these stacks (3 into 1) and setting a spacing of 8
, vertically stacking the details titles with the big stack and 8 spacing
,finally adding the title and button into the stack view with a spacing of 32.

然后我应用一些故事板约束:在本例中只是垂直和水平居中,因此视图始终居中并在两个屏幕方向上正确显示。

尽管这没有正确对齐,但这是应用堆栈和约束之前的视图,这就是我希望我的残局看起来像的样子:Looks kind of silly, but I want to figure this out so I can actually stack my paragraphs! (Image - 5).

所以现在希望我已经确定您不能真正将标签嵌入视图中,因为它在运行时无法正确呈现,并且您不能欺骗堆栈添加新行。

如何将多行标签安全地放入堆栈视图中?

这几乎是一个分支问题,但是当您尝试将堆栈应用于段落标签时,它会将标签的宽度设置为绝对巨大(有时它会抛出界面构建器无法呈现它的错误Demonstrated here (Image 6)。我已经看到这种情况发生了几次,但并不真正理解 xcode 为什么认为这是一个明智的选择。

我不想将固定宽度应用到我的标签或堆栈,因为我只会收到另一个警告,而警告很糟糕!

我完全不知道该怎么做,如果有人知道可以实现的方法,我将永远感激不已!

谢谢

这似乎真的是一个错误。

对我有用的解决方法是将多行标签嵌入视图中并将其保留在那里。

这修复了 Storyboard 编辑器上的布局,也适用于模拟器。

奇怪的是,如果我在同一个 StackView 上有多个多行标签,我只需要将其中一个嵌入到 UIView 中,然后所有其他多行标签就会正常运行。

虽然我同意这是 UIStackView 中的一个问题,因为布局应该根据 UILabel 的固有大小工作。 使用带有多行标签的堆栈视图时,无法根据标签更新其大小。 要解决此问题,请使用标签的 preferredMaxLayoutWidth 属性 并将其设置为任意值。

label.preferredMaxLayoutWidth = 1

注意:当我将它设置为 1 时,这甚至对我有用

Apple 文档中定义的 preferredMaxLayoutWidth 属性:

This property affects the size of the label when layout constraints are applied to it. During layout, if the text extends beyond the width specified by this property, the additional text flows to one or more new lines, increasing the height of the label.

我们确实希望增加垂直 UIStackView。

解决方案是将 UILabel 嵌入到 "view without inset" 中。 然后更新你的约束。