drewh drewh - 4 months ago 28
iOS Question

How do I size a UITextView to its content?

Is there a good way to adjust the size of a

UITextView
to conform to its content? Say for instance I have a
UITextView
that contains one line of text:

"Hello world"


I then add another line of text:

"Goodbye world"


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

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

Answer

This works for both iOS 6.1 and iOS 7:

- (void)textViewDidChange:(UITextView *)textView
{
    CGFloat fixedWidth = textView.frame.size.width;
    CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
    CGRect newFrame = textView.frame;
    newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
    textView.frame = newFrame;
}

Or in Swift

let fixedWidth = textView.frame.size.width
textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
var newFrame = textView.frame
newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
textView.frame = newFrame;

If you want support for iOS 6.1 then you should also:

textview.scrollEnabled = NO;
Comments