Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 537
Isuru Avatar asked Mar 08 '18 12:03

Isuru


People also ask

How do I size a UITextView to its content?

It can be done using the UITextView contentSize . This will not work if auto layout is ON. With auto layout, the general approach is to use the sizeThatFits method and update the constant value on a height constraint. CGSize sizeThatShouldFitTheContent = [_textView sizeThatFits:_textView.

How do I increase the height of a TextField in Swift?

Set the height of TextField You can use the MaxLines-MinLines property to increase TextField's total height when new text is input, and you can use the Font Size and Content Padding to increase the height and enable single-line content.


1 Answers

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)
like image 163
Peeyush karnwal Avatar answered Sep 18 '22 12:09

Peeyush karnwal