I have a UITextView called messageTextView, that is a subview of a UIView that I call messageFieldContainer.
I need to resize both my UITextView and the container UIView as the user types in more characters into the UITextView.
Here is the current method that I am using to accomplish this:
- (void)textViewDidChange:(UITextView *)textView
{
CGFloat fixedWidth = textView.frame.size.width;
CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, CGFLOAT_MAX)];
CGRect newFrame = textView.frame;
newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
if (self.previousFrameSize.height && self.previousFrameSize.height != newFrame.size.height) {
self.messageFieldContainer.frame = CGRectMake(0, self.messageFieldContainer.frame.origin.y - 20, self.messageFieldContainer.bounds.size.width, newFrame.size.height + 20);
}
self.previousFrameSize = newFrame.size;
textView.frame = newFrame;
}
I use previousFrameSizeto keep track of the changing UITextView frame size, and if the frame size ever changes then I increase the size of messageFieldContainer to accommodate the increased text view frame size.
This works perfectly most of the time, except in two situations:
- New line, first character
Here is a screen shot of what the text view looks like when a new line has started and you type the line's first character:

- New line, second character
Here is a screen shot of what the text view looks like when a new line has started and you type the line's second character:

Here is a screenshot of what the text view looks like once you type the third character of the new line. This is how it should look 100% of the time:

I need to fix this logic so that the text view always looks like the third image, even when you are typing the first or second character of a new line.
I was able to solve the new line issues by disabling
Autolayoutin mynib/xibfile and setting theUITextView'sscrollEnabledproperty toNO.Disabling
AutoLayoutmade a minor improvement, but theUITextViewwould still distort when starting a new line. The only way to solve this was to disable scrolling.Hopefully someone finds this useful. I wasted hours trying to implement complex
AutoLayoutsolutions before I found a random comment mentioning the above.