设置maximumNumberOfLines为0时UITextView内容消失问题求助
maximumNumberOfLines = 0 Hey there, let's work through why your UITextView's content vanishes when you set textContainer.maximumNumberOfLines = 0—especially with that nested layout (ScrollView → StackView → TextView) you mentioned. This is a super common gotcha with auto layout and UITextView's scrolling behavior, so here's how to fix it:
Key Fixes to Implement
1. Disable UITextView's Internal Scrolling
The biggest culprit here is almost always UITextView's default scrolling behavior. When isScrollEnabled is true, the text view doesn't resize itself to fit its content—it sticks to a fixed height and lets users scroll inside it. Pair that with maximumNumberOfLines = 0 and a parent StackView/ScrollView, and the layout system can't calculate the correct height for the text view, making content look like it's disappeared.
Add this line when configuring your UITextView:
yourTextView.isScrollEnabled = false
2. Verify Text Container & Line Break Settings
Even with maximumNumberOfLines = 0, a truncating line break mode can cause wonky behavior. Make sure your text container is set to wrap content instead:
yourTextView.textContainer.lineBreakMode = .byWordWrapping
3. Tweak StackView & ScrollView Layouts
For your vertical StackView inside the ScrollView:
- Set
stackView.distribution = .fill(or.fillProportionallyif you have other views in the stack) to let the text view expand to fit its content. - Don't set a fixed height constraint on the UITextView—this will override its auto-resizing behavior.
- Double-check your ScrollView has proper leading/trailing/top/bottom constraints to its parent view, so it can scroll correctly as content grows.
4. Force a Layout Refresh
Sometimes the layout system doesn't update right away after changing properties. Trigger a manual refresh to make sure all views resize properly:
yourTextView.layoutIfNeeded() yourStackView.layoutIfNeeded() yourScrollView.layoutIfNeeded()
Why This Works
When you turn off internal scrolling, UITextView calculates its intrinsicContentSize based on its full text content (since maximumNumberOfLines = 0 allows unlimited lines). The StackView then uses this intrinsic size to set the text view's height, and the ScrollView adjusts its content size to fit the expanded StackView—making your long text visible again.
内容的提问来源于stack exchange,提问作者papafe

