I\'ve been using the accepted answer here for years.
On iOS 7, the contentSize.height becomes the frame.height-8, regardless of text content.
What\'s a worki
If you're using iOS 7+, you can just turn on auto layout, pin each of the sides of the text view to the edge of its parent view, and it works fine. No additional code needed.
The answer given by bilobatum worked perfectly With auto layout, i.e subclassing the textview.
If you want to limit the height of the text view add another constraint (I added it using storyboard i.e. height <= 166 (height as per your need))
Then inside subclass reduce the priority of height constraint to 750 (self.heightConstraint.priority = 750) to avoid conflict between height constraint added in subclass and height constraint added on storyboard.
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.
No need to use any other API. just one line would fix all the issue.
[_textView sizeToFit];
Here, I was only concerned with height, keeping the width fixed and had missed the width constraint of my TextView in storyboard.
And this was to show up the dynamic content from the services.
Hope this might help..
I wrote a category over UITextView
:
- (CGSize)intrinsicContentSize {
return self.contentSize;
}
- (void)setContentSize:(CGSize)contentSize {
[super setContentSize:contentSize];
[self invalidateIntrinsicContentSize];
}
When UIKit
sets its contentSize
, UITextView
adjusts its intrinsic content size
. That plays nicely with autolayout
.
If you are using auto-layout, you can use the following UITextView subclass that adds an intrinsic height:
@implementation SelfSizingTextView
- (void)setText:(NSString *)text
{
[super setText:text];
[self invalidateIntrinsicContentSize];
}
- (void)setFont:(UIFont *)font
{
[super setFont:font];
[self invalidateIntrinsicContentSize];
}
- (CGSize)intrinsicContentSize
{
CGFloat width = self.frame.size.width;
CGSize size = [self sizeThatFits:CGSizeMake(width, MAXFLOAT)];
return CGSizeMake(UIViewNoIntrinsicMetric, size.height);
}
@end
Based on other answers, I made it work(in Swift). This solves the problem with newline character.
textView.sizeToFit()
textView.layoutIfNeeded()
let height = textView.sizeThatFits(CGSizeMake(textView.frame.size.width, CGFloat.max)).height
textView.contentSize.height = height
Auto Layout is needed.