1

I have a remarks section in in my project and I want to add these remarks in a UITextView. I want it so that when I add long text into the text view the entire text view grows vertically to accommodate the text.

I don't want the UITextView to scroll. Instead I want it to increase its height depending on its contents.

When we have short text I want it like this:

short text

When I add a long text to the text view it should increase its height like this:

long text

How do I implement it so the height automatically increases like this?

shim
  • 9,289
  • 12
  • 69
  • 108
Naveen Kumar
  • 177
  • 2
  • 2
  • 11

2 Answers2

1

You can get the size of the text by using NSAttributedString.

NSAttributedString *string = [[NSAttributedString alloc] initWithString:textView.text attributes:@{NSFontAttributeName:textView.font}];
float width = [string size].width;
float height = [string size].height;
// Then set the UITextView size using height and width

You could implement this in the delegate method: - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text and constantly adjust the size.

Rob Sanders
  • 5,197
  • 3
  • 31
  • 58
0

You can try with something like that:

- (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;
    textview.scrollEnabled = NO;
  }
BigK
  • 43
  • 7
  • That is the exact copy of [How do I size a UITextView to its content](http://stackoverflow.com/questions/50467/how-do-i-size-a-uitextview-to-its-content). Just reference the question rather than copying. – Rob Sanders Dec 14 '14 at 12:03