Isuru
Isuru

Reputation: 31283

Get the content height of a UITextView

I use this open source library called ReadMoreTextView to display a bunch of text. The library enables me to toggle between displaying an excerpt of the text and showing the full length content (the button is a normal UIButton added by me, not the library).

enter image description here enter image description here

This works as expected.

My problem arises when I have to display a smaller amount of text. If I add some content that doesn't exceed the height of the UITextView, I want to hide the more/less toggle button. So I thought of taking the full content height and if only it's larger than the text view's height, show the toggle button.

In the above example, I aded a long couple of paragraphs that exceeds the text view bounds. The text view's height comes up as 128. But the content height also returns 128. There's a library specific method called boundingRectForCharacterRange which is supposed to return the content height also returns a wrong value (100).

print("TEXTVIEW HEIGHT: \(textView.bounds.height)") // 128
print("CONTENT HEIGHT: \(textView.contentSize.height)") // 128

let rect = textView.layoutManager.boundingRectForCharacterRange(range: NSRange(location: 0, length: textView.text.count), inTextContainer: textView.textContainer)
print("TEXT HEIGHT: \(rect.height)") // 100

I opened an issue at the library's Github page but the owner asked to ask it here.

Why does the content height return a wrong value?

Here is the project I'm using in the above example by the way.

Upvotes: 6

Views: 6514

Answers (1)

Peeyush karnwal
Peeyush karnwal

Reputation: 642

You can simply use following method to get the content size:

let contentSize = self.textView.sizeThatFits(self.textView.bounds.size)

Then update the textview frame accordingly:

self.textView.frame = CGRect(width: contentSize.width, height: contentSize.height)

Upvotes: 10

Related Questions