How to Size the TextView in Code According to its Content in Objective C iOS

Use the following code to size the text view according to its content:

UITextView *textView;
textView = [[UITextView alloc] initWithFrame:CGRectMake(20, 35, 280, 50)];
textView.text = @"\"Gangnam Style\" is a K-pop single by South Korean musician PSY. The song was released on July 15, 2012, as the lead single of his sixth studio album PSY 6 (Six Rules), Part 1. \"Gangnam Style\" debuted at number one on the Gaon Chart, the national record chart of South Korea. As of December 2, 2012, the music video has been viewed over 874 million times on YouTube, and is the site's most watched video after surpassing Justin Bieber's single \"Baby.";
textView.font = [UIFont systemFontOfSize:15];
[self.view addSubview:textView];
CGRect frame = textView.frame;
frame.size.height = textView.contentSize.height;

First declare and initialize the UITextView object “textView” with some width and height value. You can input any height here. Set the “text” property of the textView to some random text. Then set the font property of the textView. Then add the textView as the subview of the main view. This is very important and need to done before you use the “contentSize” property.

Then declare a new CGRect variable “frame” and assign it with the value of textView.frame. Then assign the height of “frame” to textView.contentSize.height. [status_ok]”textView.contentSize.height” returns the exact height of the textView after the content has been added to it.[/status_ok] Then finally assigned the “frame” to textView.frame. So the height of the textView frame will get updated to show the full content. Remember that the width will reamin the same. So set the width accordingly while initializing the textView.

Namit Gupta

iOS Consultant at @RapidCircle. Passionate about Mobile Apps. Loves to Design. You can reach him on his social profiles below.

Comments 1

Leave a Reply