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
On
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
UITextViewwith an initial frame and add it to aUIView. - Override the
textViewDidChange:method and get aCGSizeof the content usingyourTextView.contentSizeproperty. - Use the
heightproperty of thisCGSizeto set the height of yourUITextViewusingCGRectMake.
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.
On
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
myTextViewand have it respond to changes in its text.In your view controller's interface declare that it conforms to the
UITextViewDelegateprotocol, e.g.:In your view controller's
-viewDidLoadadd this:Then implement the
-textViewDidChange:delegate method: