How can I set the height of a UITextView to exactly match its truncated content?

I have a UITextView whose height I would like to limit to some reasonable value, with the text truncating if necessary. (scrolling is disabled). How can I make sure that the height of the text view matches that of the truncated content? If, for example, I set the height to a fixed value, there will some variable space at the bottom of the text view which will affect the layout of items below it.

Is there some way to set a desired height, set and measure the truncated text, and then use that measurement to more precisely adjust the height? Is there even a way to measure the height of the displayed text within the UITextView?
There are a few ways to solve this. One thing you can try is by fixing the width with a constraint, then set the truncated string you want first, call sizeToFit() on the textView and let it lay out, then set the text to a longer string.

Here's a quick playground:

Code Block
import UIKit
import PlaygroundSupport
let textView = UITextView(frame: CGRect(x: 0, y: 0, width: 200, height: 150))
/* fix the width so the height can be adjusted */
textView.widthAnchor.constraint(equalToConstant: 200).isActive = true
let longMessage = "This is a tale of a text view that is probably going to be too small to fit this large text because it is very wordy. Hopefully this will demonstrate the issue."
textView.text = String(longMessage.prefix(100) + "...")
textView.sizeToFit()
textView.text = longMessage
PlaygroundPage.current.liveView = textView

How can I set the height of a UITextView to exactly match its truncated content?
 
 
Q