user3344977 user3344977 - 1 year ago 87
iOS Question

Resizing UITextView does not work correctly on first 2 characters of a new line

I have a

, that is a subview of a
that I call

I need to resize both my
and the container
as the user types in more characters into the

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
to keep track of the changing
frame size, and if the frame size ever changes then I increase the size of
to accommodate the increased text view frame size.

This works perfectly most of the time, except in two situations:

  1. 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:

enter image description here

  1. 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:

enter image description here

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:

enter image description here

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.

Answer Source

I was able to solve the new line issues by disabling Autolayout in my nib/xib file and setting the UITextView's scrollEnabled property to NO.

Disabling AutoLayout made a minor improvement, but the UITextView would 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 AutoLayout solutions before I found a random comment mentioning the above.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download