Is there a good way to adjust the size of a UITextView
to conform to its content? Say for instance I have a UITextView
that contains one line of text:
"Hello world"
I then add another line of text:
"Goodbye world"
Is there a good way in Cocoa Touch to get the rect
that will hold all of the lines in the text view so that I can adjust the parent view accordingly?
As another example, look at the notes' field for events in the Calendar application - note how the cell (and the UITextView
it contains) expands to hold all lines of text in the notes' string.
Hope this helps:
The Best way which I found out to re-size the height of the UITextView according to the size of the text.
or You can USE
We can do it by constraints .
2.Create IBOutlet for that height constraint.
3.don't forget to set delegate for your textview.
4.
then update your constraint like this :)
Starting with iOS 8, it is possible to use the auto layout features of a UITableView to automatically resize a UITextView with no custom code at all. I have put a project in github that demonstrates this in action, but here is the key:
rowHeight
toUITableViewAutomaticDimension
.This no longer works on iOS 7 or above
There is actually a very easy way to do resizing of the
UITextView
to its correct height of the content. It can be done using theUITextView
contentSize
.One thing to note is that the correct
contentSize
is only available after theUITextView
has been added to the view withaddSubview
. Prior to that it is equal toframe.size
This will not work if auto layout is ON. With auto layout, the general approach is to use the
sizeThatFits
method and update theconstant
value on a height constraint.heightConstraint
is a layout constraint that you typically setup via a IBOutlet by linking the property to the height constraint created in a storyboard.Just to add to this amazing answer, 2014, if you:
there is a difference in behaviour with the iPhone6+ only:
With the 6+ only (not the 5s or 6) it does add "one more blank line" to the UITextView. The "RL solution" fixes this perfectly:
It fixes the "extra line" problem on 6+.
I reviewed all the answers and all are keeping fixed width and adjust only height. If you wish to adjust also width you can very easily use this method:
so when configuring your text view, set scroll disabled
and then in delegate method
func textViewDidChange(_ textView: UITextView)
add this code:Outputs: