<p>Is there a good way to adjust the size of a <code>UITextView</code> to conform to its content? Say for instance I have a <code>UITextView</code> that contains one line of text:</p>

<pre><code>"Hello world"
</code></pre>

<p>I then add another line of text:</p>

<pre><code>"Goodbye world"
</code></pre>

<p>Is there a good way in Cocoa Touch to get the <code>rect</code> that will hold all of the lines in the text view so that I can adjust the parent view accordingly?</p>

<p>As another example, look at the notes' field for events in the Calendar application - note how the cell (and the <code>UITextView</code> it contains) expands to hold all lines of text in the notes' string.</p>

[{'answer_id': 50608, 'author': 'Mike McMaster', 'author_id': 544, 'author_profile': 'https://Stackoverflow.com/users/544', 'pm_score': 4, 'selected': False, 'text': "<p>Did you try <code>[textView sizeThatFits:textView.bounds]</code> ?</p>\n\n<p>Edit: sizeThatFits returns the size but does not actually resize the component. I'm not sure if that's what you want, or if <code>[textView sizeToFit]</code> is more what you were looking for. In either case, I do not know if it will perfectly fit the content like you want, but it's the first thing to try.</p>\n"}, {'answer_id': 107364, 'author': 'Code Addict', 'author_id': 19514, 'author_profile': 'https://Stackoverflow.com/users/19514', 'pm_score': 3, 'selected': False, 'text': '<p>Another method is the find the size a particular string will take up using the <code>NSString</code> method:</p>\n\n<p><code>-(CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size</code> </p>\n\n<p>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.</p>\n\n<p>You can then use the returned size to change the size of your view to fit.</p>\n'}, {'answer_id': 267642, 'author': 'Olie', 'author_id': 34820, 'author_profile': 'https://Stackoverflow.com/users/34820', 'pm_score': 3, 'selected': False, 'text': "<p>Combined with Mike McMaster's answer, you might want to do something like:</p>\n\n<pre><code>[myTextView setDelegate: self];\n\n...\n\n- (void)textViewDidChange:(UITextView *)textView {\n  if (myTextView == textView) {\n     // it changed.  Do resizing here.\n  }\n}\n</code></pre>\n"}, {'answer_id': 526227, 'author': 'user63934', 'author_id': 63934, 'author_profile': 'https://Stackoverflow.com/users/63934', 'pm_score': 5, 'selected': False, 'text': "<p>In my (limited) experience, </p>\n\n<pre><code>- (CGSize)sizeWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode\n</code></pre>\n\n<p>does not respect newline characters, so you can end up with a lot shorter <code>CGSize</code> than is actually required.</p>\n\n<pre><code>- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size\n</code></pre>\n\n<p>does seem to respect the newlines.</p>\n\n<p>Also, the text isn't actually rendered at the top of the <code>UITextView</code>.  In my code, I set the new height of the <code>UITextView</code> to be 24 pixels larger than the height returned by the <code>sizeOfFont</code> methods.</p>\n"}, {'answer_id': 2464437, 'author': 'Dr. Marty', 'author_id': 295891, 'author_profile': 'https://Stackoverflow.com/users/295891', 'pm_score': 1, 'selected': False, 'text': '<p>Hope this helps:</p>\n\n<pre><code>- (void)textViewDidChange:(UITextView *)textView {\n  CGSize textSize = textview.contentSize;\n  if (textSize != textView.frame.size)\n      textView.frame.size = textSize;\n}\n</code></pre>\n'}, {'answer_id': 2487402, 'author': 'Ronnie Liew', 'author_id': 1987, 'author_profile': 'https://Stackoverflow.com/users/1987', 'pm_score': 9, 'selected': False, 'text': '<h2>This no longer works on iOS 7 or above</h2>\n\n<p>There is actually a very easy way to do resizing of the <code>UITextView</code> to its correct height of the content. It can be done using the <code>UITextView</code> <code>contentSize</code>. </p>\n\n<pre><code>CGRect frame = _textView.frame;\nframe.size.height = _textView.contentSize.height;\n_textView.frame = frame;\n</code></pre>\n\n<p>One thing to note is that the correct <code>contentSize</code> is only available <strong>after</strong> the <code>UITextView</code> has been added to the view with <code>addSubview</code>. Prior to that it is equal to <code>frame.size</code></p>\n\n<p>This will not work if auto layout is ON. With auto layout, the general approach is to use the <code>sizeThatFits</code> method and update the <code>constant</code> value on a height constraint.</p>\n\n<pre><code>CGSize sizeThatShouldFitTheContent = [_textView sizeThatFits:_textView.frame.size];\nheightConstraint.constant = sizeThatShouldFitTheContent.height;\n</code></pre>\n\n<p><code>heightConstraint</code> is a layout constraint that you typically setup via a IBOutlet by linking the property to the height constraint created in a storyboard.</p>\n\n<hr>\n\n<p>Just to add to this amazing answer, 2014, if you:</p>\n\n<pre><code>[self.textView sizeToFit];\n</code></pre>\n\n<p>there is a difference in behaviour with the <strong>iPhone6+</strong> only:</p>\n\n<p><img src="https://i.stack.imgur.com/GCC09.png" alt="enter image description here"></p>\n\n<p>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:</p>\n\n<pre><code>CGRect _f = self.mainPostText.frame;\n_f.size.height = self.mainPostText.contentSize.height;\nself.mainPostText.frame = _f;\n</code></pre>\n\n<p>It fixes the "extra line" problem on 6+.</p>\n'}, {'answer_id': 5297219, 'author': 'dheeraj', 'author_id': 658572, 'author_profile': 'https://Stackoverflow.com/users/658572', 'pm_score': 3, 'selected': False, 'text': '<p>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. </p>\n\n<pre><code>UITextView *_textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 10, 300, 10)];\nNSString *str = @"This is a test text view to check the auto increment of height of a text view. This is only a test. The real data is something different.";\n_textView.text = str;\n\n[self.view addSubview:_textView];\nCGRect frame = _textView.frame;\nframe.size.height = _textView.contentSize.height;\n_textView.frame = frame;\n\nUILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(10, 5 + frame.origin.y + frame.size.height, 300, 20)];\nlbl.text = @"Hello!";\n[self.view addSubview:lbl];\n</code></pre>\n'}, {'answer_id': 11714587, 'author': 'Alejo JM', 'author_id': 545032, 'author_profile': 'https://Stackoverflow.com/users/545032', 'pm_score': 2, 'selected': False, 'text': '<p>if any other get here, this solution work for me, 1"Ronnie Liew"+4"user63934" (My text arrive from web service):\n  note the 1000 (nothing can be so big "in my case")</p>\n\n<pre><code>UIFont *fontNormal = [UIFont fontWithName:FONTNAME size:FONTSIZE];\n\nNSString *dealDescription = [client objectForKey:@"description"];\n\n//4\nCGSize textSize = [dealDescription sizeWithFont:fontNormal constrainedToSize:CGSizeMake(containerUIView.frame.size.width, 1000)];\n\nCGRect dealDescRect = CGRectMake(10, 300, containerUIView.frame.size.width, textSize.height);\n\nUITextView *dealDesc = [[[UITextView alloc] initWithFrame:dealDescRect] autorelease];\n\ndealDesc.text = dealDescription;\n//add the subview to the container\n[containerUIView addSubview:dealDesc];\n\n//1) after adding the view\nCGRect frame = dealDesc.frame;\nframe.size.height = dealDesc.contentSize.height;\ndealDesc.frame = frame;\n</code></pre>\n\n<p>And that is... Cheers</p>\n'}, {'answer_id': 12787022, 'author': 'Bill Cheswick', 'author_id': 1132993, 'author_profile': 'https://Stackoverflow.com/users/1132993', 'pm_score': 2, 'selected': False, 'text': '<p>This worked nicely when I needed to make text in a <code>UITextView</code> fit a specific area:</p>\n\n<pre>\n// The text must already be added to the subview, or contentviewsize will be wrong.\n\n- (void) reduceFontToFit: (UITextView *)tv {\n    UIFont *font = tv.font;\n    double pointSize = font.pointSize;\n\n    while (tv.contentSize.height > tv.frame.size.height && pointSize > 7.0) {\n        pointSize -= 1.0;\n        UIFont *newFont = [UIFont fontWithName:font.fontName size:pointSize];\n        tv.font = newFont;\n    }\n    if (pointSize != font.pointSize)\n        NSLog(@"font down to %.1f from %.1f", pointSize, tv.font.pointSize);\n}\n</pre>\n'}, {'answer_id': 13048177, 'author': 'Becca Royal-Gordon', 'author_id': 41222, 'author_profile': 'https://Stackoverflow.com/users/41222', 'pm_score': 3, 'selected': False, 'text': "<p>If you don't have the <code>UITextView</code> 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 a <code>UITextView</code>. For example, if you know the desired width of your text view and want to figure out the corresponding height:</p>\n\n<pre><code>NSString * string = ...;\nCGFloat textViewWidth = ...;\nUIFont * font = ...;\n\nCGSize size = CGSizeMake(textViewWidth - 8 - 8, 100000);\nsize.height = [string sizeWithFont:font constrainedToSize:size].height + 8 + 8;\n</code></pre>\n\n<p>Here, each 8 is accounting for one of the four padded edges, and 100000 just serves as a very large maximum size.</p>\n\n<p>In practice, you may want to add an extra <code>font.leading</code> 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.</p>\n"}, {'answer_id': 18651271, 'author': 'Manju', 'author_id': 2720238, 'author_profile': 'https://Stackoverflow.com/users/2720238', 'pm_score': 1, 'selected': False, 'text': '<p>The Best way which I found out to re-size the height of the UITextView according to the size of the text.</p>\n\n<pre><code>CGSize textViewSize = [YOURTEXTVIEW.text sizeWithFont:[UIFont fontWithName:@"SAMPLE_FONT" size:14.0]\n                       constrainedToSize:CGSizeMake(YOURTEXTVIEW.frame.size.width, FLT_MAX)];\n</code></pre>\n\n<p>or You can USE</p>\n\n<pre><code>CGSize textViewSize = [YOURTEXTVIEW.text sizeWithFont:[UIFont fontWithName:@"SAMPLE_FONT" size:14.0]\n                       constrainedToSize:CGSizeMake(YOURTEXTVIEW.frame.size.width, FLT_MAX) lineBreakMode:NSLineBreakByTruncatingTail];\n</code></pre>\n'}, {'answer_id': 18837714, 'author': 'phatmann', 'author_id': 201828, 'author_profile': 'https://Stackoverflow.com/users/201828', 'pm_score': 5, 'selected': False, 'text': '<p>In iOS6, you can check the <code>contentSize</code> property of UITextView right after you set the text. In iOS7, this will no longer work. If you want to restore this behavior for iOS7, place the following code in a subclass of UITextView.</p>\n\n<pre><code>- (void)setText:(NSString *)text\n{\n    [super setText:text];\n\n    if (NSFoundationVersionNumber &gt; NSFoundationVersionNumber_iOS_6_1) {\n        CGRect rect = [self.textContainer.layoutManager usedRectForTextContainer:self.textContainer];\n        UIEdgeInsets inset = self.textContainerInset;\n        self.contentSize = UIEdgeInsetsInsetRect(rect, inset).size;\n    }\n}\n</code></pre>\n'}, {'answer_id': 18908004, 'author': 'Stian Høiland', 'author_id': 659310, 'author_profile': 'https://Stackoverflow.com/users/659310', 'pm_score': 2, 'selected': False, 'text': '<p>For iOS 7.0, instead of setting the <code>frame.size.height</code> to the <code>contentSize.height</code> (which currently does nothing) use <code>[textView sizeToFit]</code>.</p>\n\n<p>See <a href="https://stackoverflow.com/a/18905603/659310">this question</a>.</p>\n'}, {'answer_id': 18931531, 'author': 'jhibberd', 'author_id': 1348198, 'author_profile': 'https://Stackoverflow.com/users/1348198', 'pm_score': 10, 'selected': True, 'text': '<p>This works for both iOS 6.1 and iOS 7:</p>\n\n<pre><code>- (void)textViewDidChange:(UITextView *)textView\n{\n    CGFloat fixedWidth = textView.frame.size.width;\n    CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];\n    CGRect newFrame = textView.frame;\n    newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);\n    textView.frame = newFrame;\n}\n</code></pre>\n\n<p>Or in Swift (Works with Swift 4.1 in iOS 11)</p>\n\n<pre><code>let fixedWidth = textView.frame.size.width\nlet newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))\ntextView.frame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)\n</code></pre>\n\n<p>If you want support for iOS 6.1 then you should also:</p>\n\n<pre><code>textview.scrollEnabled = NO;\n</code></pre>\n'}, {'answer_id': 19084234, 'author': 'madmik3', 'author_id': 291733, 'author_profile': 'https://Stackoverflow.com/users/291733', 'pm_score': 0, 'selected': False, 'text': '<p>this method seems to work for ios7   </p>\n\n<pre><code> // Code from apple developer forum - @Steve Krulewitz, @Mark Marszal, @Eric Silverberg\n- (CGFloat)measureHeight\n{\n    if ([self respondsToSelector:@selector(snapshotViewAfterScreenUpdates:)])\n    {\n    CGRect frame = internalTextView.bounds;\n    CGSize fudgeFactor;\n    // The padding added around the text on iOS6 and iOS7 is different.\n    fudgeFactor = CGSizeMake(10.0, 16.0);\n\n    frame.size.height -= fudgeFactor.height;\n    frame.size.width -= fudgeFactor.width;\n\n    NSMutableAttributedString* textToMeasure;\n    if(internalTextView.attributedText &amp;&amp; internalTextView.attributedText.length &gt; 0){\n        textToMeasure = [[NSMutableAttributedString alloc] initWithAttributedString:internalTextView.attributedText];\n    }\n    else{\n        textToMeasure = [[NSMutableAttributedString alloc] initWithString:internalTextView.text];\n        [textToMeasure addAttribute:NSFontAttributeName value:internalTextView.font range:NSMakeRange(0, textToMeasure.length)];\n    }\n\n    if ([textToMeasure.string hasSuffix:@"\\n"])\n    {\n        [textToMeasure appendAttributedString:[[NSAttributedString alloc] initWithString:@"-" attributes:@{NSFontAttributeName: internalTextView.font}]];\n    }\n\n    // NSAttributedString class method: boundingRectWithSize:options:context is\n    // available only on ios7.0 sdk.\n    CGRect size = [textToMeasure boundingRectWithSize:CGSizeMake(CGRectGetWidth(frame), MAXFLOAT)\n                                              options:NSStringDrawingUsesLineFragmentOrigin\n                                              context:nil];\n\n    return CGRectGetHeight(size) + fudgeFactor.height;\n}\nelse\n{\n    return self.internalTextView.contentSize.height;\n}\n}\n</code></pre>\n'}, {'answer_id': 24950357, 'author': 'Nikita Took', 'author_id': 2759361, 'author_profile': 'https://Stackoverflow.com/users/2759361', 'pm_score': 4, 'selected': False, 'text': '<p>I will post right solution at the bottom of the page in case someone is brave (or despaired enough) to read to this point.</p>\n\n<p>Here is gitHub repo for those, who don\'t want to read all that text: <a href="https://github.com/Nikita2k/resizableTextView" rel="noreferrer">resizableTextView</a></p>\n\n<p><strong>This works with iOs7 (and I do believe it will work with iOs8) and with autolayout. You don\'t need magic numbers, disable layout and stuff like that.</strong> Short and elegant solution.</p>\n\n<p>I think, that all constraint-related code should go to <code>updateConstraints</code> method. So, let\'s make our own <code>ResizableTextView</code>.</p>\n\n<p>The first problem we meet here is that don\'t know real content size before <code>viewDidLoad</code> method. We can take long and buggy road and calculate it based on font size, line breaks, etc. But we need robust solution, so we\'ll do:</p>\n\n<p><code>CGSize contentSize = [self sizeThatFits:CGSizeMake(self.frame.size.width, FLT_MAX)];</code></p>\n\n<p>So now we know real contentSize no matter where we are: before or after <code>viewDidLoad</code>. Now add height constraint on textView (via storyboard or code, no matter how). We\'ll adjust that value with our <code>contentSize.height</code>:</p>\n\n<pre><code>[self.constraints enumerateObjectsUsingBlock:^(NSLayoutConstraint *constraint, NSUInteger idx, BOOL *stop) {\n    if (constraint.firstAttribute == NSLayoutAttributeHeight) {\n        constraint.constant = contentSize.height;\n        *stop = YES;\n    }\n}];\n</code></pre>\n\n<p>The last thing to do is to tell superclass to <code>updateConstraints</code>.</p>\n\n<pre><code>[super updateConstraints];\n</code></pre>\n\n<p>Now our class looks like:</p>\n\n<p><strong>ResizableTextView.m</strong></p>\n\n<pre><code>- (void) updateConstraints {\n    CGSize contentSize = [self sizeThatFits:CGSizeMake(self.frame.size.width, FLT_MAX)];\n\n    [self.constraints enumerateObjectsUsingBlock:^(NSLayoutConstraint *constraint, NSUInteger idx, BOOL *stop) {\n        if (constraint.firstAttribute == NSLayoutAttributeHeight) {\n            constraint.constant = contentSize.height;\n            *stop = YES;\n        }\n    }];\n\n    [super updateConstraints];\n}\n</code></pre>\n\n<p>Pretty and clean, right? And you don\'t have to deal with that code in your <strong>controllers</strong>!</p>\n\n<p><strong>But wait!</strong>\n<strong>Y NO ANIMATION!</strong></p>\n\n<p>You can easily animate changes to make <code>textView</code> stretch smoothly. Here is an example:</p>\n\n<pre><code>    [self.view layoutIfNeeded];\n    // do your own text change here.\n    self.infoTextView.text = [NSString stringWithFormat:@"%@, %@", self.infoTextView.text, self.infoTextView.text];\n    [self.infoTextView setNeedsUpdateConstraints];\n    [self.infoTextView updateConstraintsIfNeeded];\n    [UIView animateWithDuration:1 delay:0 options:UIViewAnimationOptionLayoutSubviews animations:^{\n        [self.view layoutIfNeeded];\n    } completion:nil];\n</code></pre>\n'}, {'answer_id': 26599389, 'author': 'Brett Donald', 'author_id': 2518285, 'author_profile': 'https://Stackoverflow.com/users/2518285', 'pm_score': 7, 'selected': False, 'text': "<h2>Update</h2>\n<p>The key thing you need to do is turn off scrolling in your UITextView.</p>\n<pre><code>myTextView.scrollEnabled = @NO\n</code></pre>\n<h2>Original Answer</h2>\n<p>To make a dynamically sizing <code>UITextView</code> inside a <code>UITableViewCell</code>, I found the following combination works in Xcode 6 with the iOS 8 SDK:</p>\n<ul>\n<li><p>Add a <code>UITextView</code> to a <code>UITableViewCell</code> and constrain it to the sides</p>\n</li>\n<li><p>Set the <code>UITextView</code>'s <code>scrollEnabled</code> property to <code>NO</code>. With scrolling enabled, the frame of the <code>UITextView</code> is independent of its content size, but with scrolling disabled, there is a relationship between the two.</p>\n</li>\n<li><p>If your table is using the original default row height of 44 then it will automatically calculate row heights, but if you changed the default row height to something else, you may need to manually switch on auto-calculation of row heights in <code>viewDidLoad</code>:</p>\n<pre><code> tableView.estimatedRowHeight = 150;\n tableView.rowHeight = UITableViewAutomaticDimension;\n</code></pre>\n</li>\n</ul>\n<p>For read-only dynamically sizing <code>UITextView</code>s, that’s it. If you’re allowing users to edit the text in your <code>UITextView</code>, you also need to:</p>\n<ul>\n<li><p>Implement the <code>textViewDidChange:</code> method of the <code>UITextViewDelegate</code> protocol, and tell the <code>tableView</code> to repaint itself every time the text is edited:</p>\n<pre><code> - (void)textViewDidChange:(UITextView *)textView;\n {\n     [tableView beginUpdates];\n     [tableView endUpdates];\n }\n</code></pre>\n</li>\n<li><p>And don’t forget to set the <code>UITextView</code> delegate somewhere, either in <code>Storyboard</code> or in <code>tableView:cellForRowAtIndexPath:</code></p>\n</li>\n</ul>\n"}, {'answer_id': 27218598, 'author': 'Gal Blank', 'author_id': 662469, 'author_profile': 'https://Stackoverflow.com/users/662469', 'pm_score': 1, 'selected': False, 'text': '<p>For those who want the textview to actually move up and maintain the bottom line position</p>\n\n<pre><code>CGRect frame = textView.frame;\nframe.size.height = textView.contentSize.height;\n\nif(frame.size.height &gt; textView.frame.size.height){\n    CGFloat diff = frame.size.height - textView.frame.size.height;\n    textView.frame = CGRectMake(0, textView.frame.origin.y - diff, textView.frame.size.width, frame.size.height);\n}\nelse if(frame.size.height &lt; textView.frame.size.height){\n    CGFloat diff = textView.frame.size.height - frame.size.height;\n    textView.frame = CGRectMake(0, textView.frame.origin.y + diff, textView.frame.size.width, frame.size.height);\n}\n</code></pre>\n'}, {'answer_id': 27625246, 'author': 'Gal Blank', 'author_id': 662469, 'author_profile': 'https://Stackoverflow.com/users/662469', 'pm_score': -1, 'selected': False, 'text': '<p>Not sure why people always over complicate things:\nhere it is :</p>\n\n<pre><code>- (void)textViewDidChange:(UITextView *)textView{ CGRect frame = textView.frame;\nCGFloat height = [self measureHeightOfUITextView:textView];\nCGFloat insets = textView.textContainerInset.top + textView.textContainerInset.bottom;\nheight += insets;\nframe.size.height = height;\n\nif(frame.size.height &gt; textView.frame.size.height){\n    CGFloat diff = frame.size.height - textView.frame.size.height;\n    textView.frame = CGRectMake(5, textView.frame.origin.y - diff, textView.frame.size.width, frame.size.height);\n}\nelse if(frame.size.height &lt; textView.frame.size.height){\n    CGFloat diff = textView.frame.size.height - frame.size.height;\n    textView.frame = CGRectMake(5, textView.frame.origin.y + diff, textView.frame.size.width, frame.size.height);\n}\n[textView setNeedsDisplay];\n}\n</code></pre>\n'}, {'answer_id': 27738557, 'author': 'Swaroop S', 'author_id': 2173072, 'author_profile': 'https://Stackoverflow.com/users/2173072', 'pm_score': 3, 'selected': False, 'text': "<p>Guys using autolayout and your sizetofit isn't working, then please check your width constraint once. If you had missed the width constraint then the height will be accurate.</p>\n\n<p>No need to use any other API. just one line would fix all the issue.</p>\n\n<pre><code>[_textView sizeToFit];\n</code></pre>\n\n<p>Here, I was only concerned with height, keeping the width fixed and had missed the width constraint of my TextView in storyboard.</p>\n\n<p>And this was to show up the dynamic content from the services.</p>\n\n<p>Hope this might help..</p>\n"}, {'answer_id': 28916825, 'author': 'Fareed Alnamrouti', 'author_id': 427622, 'author_profile': 'https://Stackoverflow.com/users/427622', 'pm_score': 2, 'selected': False, 'text': '<p>here is the swift version of @jhibberd</p>\n\n<pre><code>    let cell:MsgTableViewCell! = self.tableView.dequeueReusableCellWithIdentifier("MsgTableViewCell", forIndexPath: indexPath) as? MsgTableViewCell\n    cell.msgText.text = self.items[indexPath.row]\n    var fixedWidth:CGFloat = cell.msgText.frame.size.width\n    var size:CGSize = CGSize(width: fixedWidth,height: CGFloat.max)\n    var newSize:CGSize = cell.msgText.sizeThatFits(size)\n    var newFrame:CGRect = cell.msgText.frame;\n    newFrame.size = CGSizeMake(CGFloat(fmaxf(Float(newSize.width), Float(fixedWidth))), newSize.height);\n    cell.msgText.frame = newFrame\n    cell.msgText.frame.size = newSize        \n    return cell\n</code></pre>\n'}, {'answer_id': 29509538, 'author': 'Mohammad Zekrallah', 'author_id': 3492881, 'author_profile': 'https://Stackoverflow.com/users/3492881', 'pm_score': 1, 'selected': False, 'text': "<p>The only code that will work is the one that uses 'SizeToFit' as in jhibberd answer above but actually it won't pick up unless you call it in <strong>ViewDidAppear</strong> or wire it to UITextView text changed event.</p>\n"}, {'answer_id': 30215237, 'author': 'Apfelsaft', 'author_id': 1447641, 'author_profile': 'https://Stackoverflow.com/users/1447641', 'pm_score': 1, 'selected': False, 'text': "<p>Based on Nikita Took's answer I came to the following solution in Swift which works on iOS 8 with autolayout:</p>\n\n<pre><code>    descriptionTxt.scrollEnabled = false\n    descriptionTxt.text = yourText\n\n    var contentSize = descriptionTxt.sizeThatFits(CGSizeMake(descriptionTxt.frame.size.width, CGFloat.max))\n    for c in descriptionTxt.constraints() {\n        if c.isKindOfClass(NSLayoutConstraint) {\n            var constraint = c as! NSLayoutConstraint\n            if constraint.firstAttribute == NSLayoutAttribute.Height {\n                constraint.constant = contentSize.height\n                break\n            }\n        }\n    }\n</code></pre>\n"}, {'answer_id': 30281699, 'author': 'RawMean', 'author_id': 342646, 'author_profile': 'https://Stackoverflow.com/users/342646', 'pm_score': 1, 'selected': False, 'text': '<p>Swift answer:\nThe following code computes the height of your textView.  </p>\n\n<pre><code>                let maximumLabelSize = CGSize(width: Double(textView.frame.size.width-100.0), height: DBL_MAX)\n                let options = NSStringDrawingOptions.TruncatesLastVisibleLine | NSStringDrawingOptions.UsesLineFragmentOrigin\n                let attribute = [NSFontAttributeName: textView.font!]\n                let str = NSString(string: message)\n                let labelBounds = str.boundingRectWithSize(maximumLabelSize,\n                    options: NSStringDrawingOptions.UsesLineFragmentOrigin,\n                    attributes: attribute,\n                    context: nil)\n                let myTextHeight = CGFloat(ceilf(Float(labelBounds.height)))\n</code></pre>\n\n<p>Now you can set the height of your textView to <code>myTextHeight</code></p>\n'}, {'answer_id': 30650613, 'author': 'Chuck Krutsinger', 'author_id': 1256015, 'author_profile': 'https://Stackoverflow.com/users/1256015', 'pm_score': 3, 'selected': False, 'text': '<p>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 <a href="https://github.com/ksoftllc/UITableView-with-UITextView-and-UILabel-Resize" rel="noreferrer">github</a> that demonstrates this in action, but here is the key:</p>\n\n<ol>\n<li>The UITextView must have scrolling disabled, which you can do programmatically or through the interface builder. It will not resize if scrolling is enabled because scrolling lets you view the larger content.</li>\n<li>In viewDidLoad for the UITableViewController, you must set a value for estimatedRowHeight and then set the <code>rowHeight</code> to <code>UITableViewAutomaticDimension</code>.</li>\n</ol>\n\n<pre><code>\n- (void)viewDidLoad {\n    [super viewDidLoad];\n    self.tableView.estimatedRowHeight = self.tableView.rowHeight;\n    self.tableView.rowHeight = UITableViewAutomaticDimension;\n}\n</code></pre>\n\n<ol start="3">\n<li>The project deployment target must be iOS 8 or greater. </li>\n</ol>\n'}, {'answer_id': 32894513, 'author': 'Juan Boero', 'author_id': 1634890, 'author_profile': 'https://Stackoverflow.com/users/1634890', 'pm_score': 6, 'selected': False, 'text': '<p><strong>Swift   :</strong></p>\n\n<pre><code>textView.sizeToFit()\n</code></pre>\n'}, {'answer_id': 33275688, 'author': 'Andrea', 'author_id': 395897, 'author_profile': 'https://Stackoverflow.com/users/395897', 'pm_score': 0, 'selected': False, 'text': "<p>The easiest way to ask a <code>UITextView</code> is just calling <code>-sizeToFit</code>it should work also with <code>scrollingEnabled = YES</code>, after that check for the height and add a height constraint on the text view with the same value.<br>\nPay attention that <code>UITexView</code> contains insets, this means that you can't ask the string object how much space it want to use, because this is just the bounding rect of the text.<br>\nAll the person that are experiencing wrong size using <code>-sizeToFit</code> it's probably due to the fact that the text view has not been layout yet to the interface size.<br>\nThis always happen when you use size classes and a <code>UITableView</code>, the first time cells are created in the <code>- tableView:cellForRowAtIndexPath:</code> the comes out with the size of the any-any configuration, if you compute you value just now the text view will have a different width than the expected and this will screw all sizes.<br>\nTo overcome this issue I've found useful to override the <code>-layoutSubviews</code> method of the cell to recalculate textview height.<br></p>\n"}, {'answer_id': 33475313, 'author': 'Bartłomiej Semańczyk', 'author_id': 2725435, 'author_profile': 'https://Stackoverflow.com/users/2725435', 'pm_score': 3, 'selected': False, 'text': '<p>The following things are enough:</p>\n\n<ol>\n<li>Just remember to set <strong>scrolling enabled</strong> to <strong>NO</strong> for your <code>UITextView</code>:</li>\n</ol>\n\n<p><a href="https://i.stack.imgur.com/Xuv3Z.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Xuv3Z.png" alt="enter image description here"></a></p>\n\n<ol start="2">\n<li>Properly set Auto Layout Constraints.</li>\n</ol>\n\n<p>You may even use <code>UITableViewAutomaticDimension</code>.</p>\n'}, {'answer_id': 34975206, 'author': 'jithin', 'author_id': 5264832, 'author_profile': 'https://Stackoverflow.com/users/5264832', 'pm_score': 0, 'selected': False, 'text': '<p>If you are using scrollview and content view,and you want to increase the height depending the TextView content height,then this piece of code will help you.</p>\n\n<p><strong>Hope this will help,it worked perfectly in iOS9.2</strong></p>\n\n<p>and of course set <code>textview.scrollEnabled = NO;</code></p>\n\n<pre><code>-(void)adjustHeightOfTextView\n{\n    //this pieces of code will helps to adjust the height of the uitextview View W.R.T content\n    //This block of code work will calculate the height of the textview text content height and calculate the height for the whole content of the view to be displayed.Height --&gt; 400 is fixed,it will change if you change anything in the storybord.\n\n\nCGSize textViewSize = [self.textview sizeThatFits:CGSizeMake(self.view.frame.size.width, self.view.frame.size.height)];//calulcate the content width and height\n\nfloat textviewContentheight =textViewSize.height;\nself.scrollview.contentSize = CGSizeMake(self.textview.frame.size.width,textviewContentheight + 400);//height value is passed\nself.scrollview.frame =CGRectMake(self.scrollview.frame.origin.x, self.scrollview.frame.origin.y, self.scrollview.frame.size.width, textviewContentheight+400);\n\nCGRect Frame = self.contentview.frame;\nFrame.size.height = textviewContentheight + 400;\n[self.contentview setFrame:Frame];\n\nself.textview.frame =CGRectMake(self.textview.frame.origin.x, self.textview.frame.origin.y, self.textview.frame.size.width, textviewContentheight);\n[ self.textview setContentSize:CGSizeMake( self.textview.frame.size.width,textviewContentheight)];\nself.contenview_heightConstraint.constant = \n\nself.scrollview.bounds.size.height;\n    NSLog(@"%f",self.contenview_heightConstraint.constant);\n}\n</code></pre>\n'}, {'answer_id': 35790169, 'author': 'Kishore Kumar', 'author_id': 5105555, 'author_profile': 'https://Stackoverflow.com/users/5105555', 'pm_score': 3, 'selected': False, 'text': '<p>We can do it by constraints .</p>\n\n<ol>\n<li>Set Height constraints for UITextView.\n<a href="https://i.stack.imgur.com/mKaOJ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/mKaOJ.png" alt="enter image description here"></a></li>\n</ol>\n\n<p>2.Create IBOutlet for that height constraint.</p>\n\n<pre><code> @property (weak, nonatomic) IBOutlet NSLayoutConstraint *txtheightconstraints;\n</code></pre>\n\n<p>3.don\'t forget to set delegate for your textview.</p>\n\n<p>4.</p>\n\n<pre><code>-(void)textViewDidChange:(UITextView *)textView\n{\n    CGFloat fixedWidth = textView.frame.size.width;\n    CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];\n    CGRect newFrame = textView.frame;\n    newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);\n    NSLog(@"this is updating height%@",NSStringFromCGSize(newFrame.size));\n    [UIView animateWithDuration:0.2 animations:^{\n                  _txtheightconstraints.constant=newFrame.size.height;\n    }];\n\n}\n</code></pre>\n\n<p>then update your constraint like this :)</p>\n'}, {'answer_id': 38418756, 'author': 'Alok', 'author_id': 3024579, 'author_profile': 'https://Stackoverflow.com/users/3024579', 'pm_score': 7, 'selected': False, 'text': '<p>Very easy working solution using code and storyboard both. </p>\n\n<p>By Code</p>\n\n<pre><code>textView.scrollEnabled = false\n</code></pre>\n\n<p>By Storyboard</p>\n\n<p>Uncheck the <strong>Scrolling Enable</strong></p>\n\n<p><a href="https://i.stack.imgur.com/CGWqW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/CGWqW.png" alt="enter image description here"></a></p>\n\n<p>No need to do anything apart of this.</p>\n'}, {'answer_id': 42928806, 'author': 'Peter Stajger', 'author_id': 296649, 'author_profile': 'https://Stackoverflow.com/users/296649', 'pm_score': 3, 'selected': False, 'text': '<p>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:</p>\n\n<p>so when configuring your text view, set scroll disabled</p>\n\n<pre><code>textView.isScrollEnabled = false\n</code></pre>\n\n<p>and then in delegate method <code>func textViewDidChange(_ textView: UITextView)</code> add this code:</p>\n\n<pre><code>func textViewDidChange(_ textView: UITextView) {\n    let newSize = textView.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))\n    textView.frame = CGRect(origin: textView.frame.origin, size: newSize)\n}\n</code></pre>\n\n<p>Outputs:</p>\n\n<p><a href="https://i.stack.imgur.com/NFe0a.png" rel="noreferrer"><img src="https://i.stack.imgur.com/NFe0a.png" alt="enter image description here"></a></p>\n\n<p><a href="https://i.stack.imgur.com/k40zg.png" rel="noreferrer"><img src="https://i.stack.imgur.com/k40zg.png" alt="enter image description here"></a></p>\n'}, {'answer_id': 43137430, 'author': 'Volodymyr Nazarkevych', 'author_id': 5360675, 'author_profile': 'https://Stackoverflow.com/users/5360675', 'pm_score': 1, 'selected': False, 'text': '<p>Here is the answer if you need resize <code>textView</code> and <code>tableViewCell</code> dynamically in <code>staticTableView</code></p>\n\n<p>[<a href="https://stackoverflow.com/a/43137182/5360675][1]">https://stackoverflow.com/a/43137182/5360675][1]</a></p>\n'}, {'answer_id': 46398555, 'author': 'iOS Flow', 'author_id': 3922498, 'author_profile': 'https://Stackoverflow.com/users/3922498', 'pm_score': 1, 'selected': False, 'text': '<p>Works like a charm on ios 11\nand I\'m working in a cell, like a chat cell with bubble.</p>\n\n<pre><code>let content = UITextView(frame: CGRect(x: 4, y: 4, width: 0, height: 0))\ncontent.text = "what ever short or long text you wanna try"\ncontent.textAlignment = NSTextAlignment.left\ncontent.font = UIFont.systemFont(ofSize: 13)\nlet spaceAvailable = 200 //My cell is fancy I have to calculate it...\nlet newSize = content.sizeThatFits(CGSize(width: CGFloat(spaceAvailable), height: CGFloat.greatestFiniteMagnitude))\ncontent.isEditable = false\ncontent.dataDetectorTypes = UIDataDetectorTypes.all\ncontent.isScrollEnabled = false\ncontent.backgroundColor = UIColor.clear\nbkgView.addSubview(content)\n</code></pre>\n'}, {'answer_id': 48188184, 'author': 'ali ozkara', 'author_id': 4362167, 'author_profile': 'https://Stackoverflow.com/users/4362167', 'pm_score': 3, 'selected': False, 'text': '<p>disable scrolling</p>\n\n<p><a href="https://i.stack.imgur.com/60exo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/60exo.png" alt=""></a></p>\n\n<p>add constaints</p>\n\n<p><a href="https://i.stack.imgur.com/lH2fW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lH2fW.png" alt=""></a></p>\n\n<p>and add your text </p>\n\n<pre><code>[yourTextView setText:@"your text"];\n[yourTextView layoutIfNeeded];\n</code></pre>\n\n<p>if you use <code>UIScrollView</code> you should add this too;</p>\n\n<pre><code>[yourScrollView layoutIfNeeded];\n\n-(void)viewDidAppear:(BOOL)animated{\n    CGRect contentRect = CGRectZero;\n\n    for (UIView *view in self.yourScrollView.subviews) {\n         contentRect = CGRectUnion(contentRect, view.frame);\n    }\n    self.yourScrollView.contentSize = contentRect.size;\n}\n</code></pre>\n'}, {'answer_id': 51416071, 'author': 'Vakas', 'author_id': 3627468, 'author_profile': 'https://Stackoverflow.com/users/3627468', 'pm_score': -1, 'selected': False, 'text': '<p>Here are the steps</p>\n\n<p>Solution works on all versions of iOS. Swift 3.0 and above. </p>\n\n<ol>\n<li>Add your <code>UITextView</code> to the <code>View</code>. I\'m adding it with code, you can add via interface builder.</li>\n<li>Add constraints. I\'m adding the constraints in code, you can do it in interface builder as well.</li>\n<li>Use <code>UITextViewDelegate</code> method <code>func textViewDidChange(_ textView: UITextView)</code> to adjust the size of the TextView</li>\n</ol>\n\n<p><strong>Code :</strong> </p>\n\n<ol>\n<li><pre><code>//1. Add your UITextView in ViewDidLoad\nlet textView = UITextView()\ntextView.frame = CGRect(x: 0, y: 0, width: 200, height: 100)\ntextView.backgroundColor = .lightGray\ntextView.text = "Here is some default text."\n\n\n\n//2. Add constraints\ntextView.translatesAutoresizingMaskIntoConstraints = false\n[\ntextView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),\ntextView.leadingAnchor.constraint(equalTo: view.leadingAnchor),\ntextView.trailingAnchor.constraint(equalTo: view.trailingAnchor),\ntextView.heightAnchor.constraint(equalToConstant: 50),\ntextView.widthAnchor.constraint(equalToConstant: 30)\n].forEach{ $0.isActive = true }\n\ntextView.font = UIFont.preferredFont(forTextStyle: .headline)\n\ntextView.delegate = self\ntextView.isScrollEnabled = false\n\ntextViewDidChange(textView)\n\n\n//3. Implement the delegate method.\nfunc textViewDidChange(_ textView: UITextView) {\nlet size = CGSize(width: view.frame.width, height: .infinity)\nlet estimatedSize = textView.sizeThatFits(size)\n\ntextView.constraints.forEach { (constraint) in\n    if constraint.firstAttribute == .height {\n        print("Height: ", estimatedSize.height)\n        constraint.constant = estimatedSize.height\n    }\n}\n}\n</code></pre></li>\n</ol>\n'}, {'answer_id': 57739436, 'author': 'Jonathan.', 'author_id': 191463, 'author_profile': 'https://Stackoverflow.com/users/191463', 'pm_score': 0, 'selected': False, 'text': "<p>It's quite easy with Key Value Observing (KVO), just create a subclass of UITextView and do:</p>\n\n<pre><code>private func setup() { // Called from init or somewhere\n\n    fitToContentObservations = [\n        textView.observe(\\.contentSize) { _, _ in\n            self.invalidateIntrinsicContentSize()\n        },\n        // For some reason the content offset sometimes is non zero even though the frame is the same size as the content size.\n        textView.observe(\\.contentOffset) { _, _ in\n            if self.contentOffset != .zero { // Need to check this to stop infinite loop\n                self.contentOffset = .zero\n            }\n        }\n    ]\n}\npublic override var intrinsicContentSize: CGSize {\n    return contentSize\n}\n</code></pre>\n\n<p>If you don't want to subclass you could try doing <code>textView.bounds = textView.contentSize</code> in the <code>contentSize</code> observer.</p>\n"}, {'answer_id': 59250215, 'author': 'atereshkov', 'author_id': 5969121, 'author_profile': 'https://Stackoverflow.com/users/5969121', 'pm_score': 2, 'selected': False, 'text': '<p>This works fine for <strong>Swift 5</strong> in case you want to fit your TextView once user write text on the fly.</p>\n\n<p>Just implement <strong>UITextViewDelegate</strong> with:</p>\n\n<pre><code>func textViewDidChange(_ textView: UITextView) {\n    let newSize = textView.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))\n    textView.frame.size = CGSize(width: newSize.width, height: newSize.height)\n}\n</code></pre>\n'}, {'answer_id': 60439398, 'author': 'f0go', 'author_id': 2543967, 'author_profile': 'https://Stackoverflow.com/users/2543967', 'pm_score': 3, 'selected': False, 'text': '<p>Using UITextViewDelegate is the easiest way:</p>\n\n<pre><code>func textViewDidChange(_ textView: UITextView) {\n    textView.sizeToFit()\n    textviewHeight.constant = textView.contentSize.height\n}\n</code></pre>\n'}, {'answer_id': 66250012, 'author': 'iOS_Mouse', 'author_id': 6748722, 'author_profile': 'https://Stackoverflow.com/users/6748722', 'pm_score': 0, 'selected': False, 'text': "<p>The simplest solution that worked for me was to put a height constraint on the textView in the Storyboard, then connect the textView and height constraint to the code:</p>\n<pre><code>@IBOutlet var myAwesomeTextView: UITextView!\n@IBOutlet var myAwesomeTextViewHeight: NSLayoutConstraint!\n</code></pre>\n<p>Then after setting the text and paragraph styles, add this in <strong>viewDidAppear</strong>:</p>\n<pre><code>self.myAwesomeTextViewHeight.constant = self.myAwesomeTextView.contentSize.height\n</code></pre>\n<p>Some notes:</p>\n<ol>\n<li>In contrast to other solutions, <strong>isScrollEnabled must to be set to true</strong> in order for this to work.</li>\n<li>In my case, I was setting custom attributes to the font inside the code, therefore I had to set the height in viewDidAppear (it wouldn't work properly before that). If you aren't changing any text attributes in code, you should be able to set the height in viewDidLoad or anywhere after setting the text.</li>\n</ol>\n"}, {'answer_id': 66501024, 'author': 'Hex Bob-omb', 'author_id': 1840120, 'author_profile': 'https://Stackoverflow.com/users/1840120', 'pm_score': 0, 'selected': False, 'text': '<p>Looks like this guy figured it out for NSTextView and his answer applies to iOS too. Turns out intrinsicContentSize doesn’t sync up with the layout manager. If a layout happens after intrinsicContentSize you could have a discrepancy.</p>\n<p>He has an easy fix.</p>\n<p><a href="https://stackoverflow.com/questions/47927844/nstextview-in-nsoutlineview-with-intrinsiccontentsize-setting-wrong-height">NSTextView in NSOutlineView with IntrinsicContentSize setting wrong height</a></p>\n'}]
['https://Stackoverflow.com/questions/50467', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1967/']