I did a lot of research but none helped with my current situation. What I want to do is have an auto resizing UITextView
that grows as the user types. It starts off with a default height and auto grows as the text increases. I added to UITextView
to my UIView
using the interface builder
. now I just need help with making it auto grow. The answers I found said in IOS7 you use [myTextView sizeToFit]
which makes it auto-resize
but looks like this only works for UITextViews
that are added programmatically
.
Autoresizing UITextView IOS7
3k views Asked by emm AtThere are 3 answers
I would suggest you try HPGrowingTextView
before using a custom solution.
In case you do not like it, you would go about it like this:
- Create a
UITextView
with an initial frame and add it to aUIView
. - Override the
textViewDidChange:
method and get aCGSize
of the content usingyourTextView.contentSize
property. - Use the
height
property of thisCGSize
to set the height of yourUITextView
usingCGRectMake
.
The contentSize
gives you the exact size of the content in your textView, without using sizeWithFont:
(deprecated) or sizeWithAttributes:
.
But here's the catch: If your textView
is contained inside another UIView
, you might have to set it's autoresizingMasks
to UIViewAutoresizingFlexibleTopMargin
, UIViewAutoresizingFlexibleBottomMargin
, UIViewAutoresizingFlexibleHeight
as per your need, for the succesful resizing of superviews of the textView.
Try going through the code of HPGrowingTextView
, and you will understand how this behaviour is implemented.
I made a subclass of UITextView just for that:
https://github.com/MatejBalantic/MBAutoGrowingTextView
It is an auto-layout based light-weight UITextView subclass which automatically grows and shrinks based on the size of user input and can be constrained by maximal and minimal height - all without a single line of code.
Made primarily for use in Interface builder and only works with Auto layout.
You will need to set a delegate for
myTextView
and have it respond to changes in its text.In your view controller's interface declare that it conforms to the
UITextViewDelegate
protocol, e.g.:In your view controller's
-viewDidLoad
add this:Then implement the
-textViewDidChange:
delegate method: