Issue
I am experiencing a weird behaviour with a UITextView
which is inside a UIStackView
with a defined spacing of 0
. The UITextView
is used to display a message inside a chat bubble. When the message is only one line, the UITextView
expands and adds a bottom spacing/padding of about 2.3 px
. Looking at the view hierarchy, the text itself is a _UITextLayoutFragmentView
which is inside a _UITextLayoutCanvasView
. It appears that this canvas view is drawn too big, causing the spacing.
The following images are from the view hierarchy with a one line message where the issue appears and from a message with two lines, where the issue is not appearing: https://imgur.com/a/nvrNYZM (Link since I cannot post images on Stackoverflow yet).
What I tried
I already set the UITextView
insets with:
messageTextView.textContainerInset = .zero
messageTextView.textContainer.lineFragmentPadding = .zero
messageTextView.contentInset = .zero
which removed the normal padding the UITextView
has (using this answer/thread).
My initial thought was that the messageTextView
has a minimum height specified somewhere, which causes the view to expand when the text inside (one line) does not fill the minimum height. However I don’t know if thats correct or if there’s even a possibility to change a minimum height. Shrinking the font size creates a bigger spacing.
The chat bubble uses UIStackViews
to automatically adjust its size to the contents. Before changing to a UITextView
we used an UILabel
which worked fine and did not create any spacing.
Has anybody experienced a similar issue?
2
Answers
https://github.com/KennethTsang/GrowingTextView
The layout you’ve shown appears correct… but something is not-quite-right.
I put this together as a quick test – it should be pretty close to what you have…
How the cell xib looks in IB:
How it looks when running – 5 "messages" related twice. The first set has the "documentsStack and imagesStack" hidden, the second set they are showing (with no subviews, but with 10-point height constraint):
and here’s the Debug View Hierarchy look:
So… source for the xib:
The "text view acting like a label" class
Cell class
and sample controller