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.
I found out a way to resize the height of a text field according to the text inside it and also arrange a label below it based on the height of the text field! Here is the code.
Another method is the find the size a particular string will take up using the
NSString
method:-(CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size
This returns the size of the rectangle that fits the given string with the given font. Pass in a size with the desired width and a maximum height, and then you can look at the height returned to fit the text. There is a version that lets you specify line break mode also.
You can then use the returned size to change the size of your view to fit.
If you don't have the
UITextView
handy (for example, you're sizing table view cells), you'll have to calculate the size by measuring the string, then accounting for the 8 pt of padding on each side of aUITextView
. For example, if you know the desired width of your text view and want to figure out the corresponding height:Here, each 8 is accounting for one of the four padded edges, and 100000 just serves as a very large maximum size.
In practice, you may want to add an extra
font.leading
to the height; this adds a blank line below your text, which may look better if there are visually heavy controls directly beneath the text view.Based on Nikita Took's answer I came to the following solution in Swift which works on iOS 8 with autolayout:
This works for both iOS 6.1 and iOS 7:
Or in Swift (Works with Swift 4.1 in iOS 11)
If you want support for iOS 6.1 then you should also:
Combined with Mike McMaster's answer, you might want to do something like: