动态大小、启用滚动的 UITextView 的自动布局问题

Autolayout issue with dynamically sized, scrolling-enabled UITextView

这是我想要的:

+-------------------------+   +-------------------------+
| +---------------------+ |   | +---------------------+ |
| |        UILabel      | |   | |        UILabel      | |
| +---------------------+ |   | +---------------------+ |
|                         |   |                         |
| +---------------------+ |   | +---------------------+ |
| | UITextView; height  | |   | | UITextView; height || |
| | depends on content  | |   | | depends on content || |
| +---------------------+ |   | | This one here has  || |
|                         |   | | so much text that   | |
| +---------------------+ |   | | the complete text   | |
| |       UIButton      | |   | | can only be seen by | |
| +---------------------+ |   | | scrolling: Text Te… | |
|                         |   | +---------------------+ |
|                         |   |                         |
|                         |   | +---------------------+ |
|                         |   | |       UIButton      | |
|                         |   | +---------------------+ |
+-------------------------+   +-------------------------+

所有元素都存在于一个普通的 UIView 中。

UILabel 和 UIButton 的高度是固定的。 UITextView 应该与其内容一样高。即使对于非常长的文本,其高度也不应将以下元素推离屏幕。

我目前拥有的:

使用此设置,根本不会显示 UITextView。如果我为 UITextView 设置最小高度,它会以该高度显示,但高度不会根据内容进行调整。如果我禁用滚动,则 UITextView 的高度会得到适当调整。

我可以有一个内容感知、滚动的 UITextView 吗?这可以通过 AutoLayout 完成吗?如果是,如何?

不幸的是,没有 "auto" 方法 enabling/disabling UITextView 以您想要的方式滚动。

一种选择是确定文本视图的最大高度,然后使用观察器观察文本视图的变化 contentSize。当 contentSize 高度超过您的最大高度时,启用滚动。有关更多详细信息(以及示例项目的 link),请参阅此答案:

另一种选择是在可滚动的 UIScrollView 中嵌入非滚动的 UITextView。诀窍是将滚动视图的高度限制为文本视图的高度,但将其优先级设置为 250。将所有其他约束设置为正常。滚动视图的高度会随着文本视图的变化而扩展以匹配文本视图的高度,但其他约束会限制它,因此它不会继续增长。