3

I have a textView which insert different texts with different lengths, some are short and others are long.. The UITextView is subviews of a scrollView. How can I dynamically set the height of UITextView according to the length of the entered text?

This code in ViewDidLoad doesn't work:

self.textView.contentSize = [self.textView.text sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(100, self.textView.contentSize.height) lineBreakMode:UIViewAutoresizingFlexibleHeight];

4 Answers4

3

This does not work because your contraint is the current contentSize of the TextView. You should put the maximum size that you want.

For example your code could be like this :

#define kMaxHeight 100.f
self.textView.contentSize = [self.textView.text sizeWithFont:[UIFont systemFontOfSize:14] 
                                           constrainedToSize:CGSizeMake(100, kMaxHeight) 
                                               lineBreakMode:UIViewAutoresizingFlexibleHeight];

Hope this helps

iGranDav
  • 2,420
  • 1
  • 19
  • 23
2

As UITextView is a subclass of UIScrollView , so may be this will be helpful:

UITextView *textView = [UITextView new];
textView.text = @"Your texts ......";
CGSize contentSize = textView.contentSize ;
CGRect frame = textView.frame ;
frame.size.height = contentSize.height ;
textView.frame = frame ;
monjer
  • 2,689
  • 2
  • 19
  • 28
2

Below coding is working.Please try it

// leave the width at 300 otherwise the height wont measure correctly
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(10.0f, 0.0f, 300.0f, 100.0f)];

// add text to the UITextView first so we know what size to make it
textView.text = [_dictSelected objectForKey:@"body"];

// get the size of the UITextView based on what it would be with the text
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;
Paebbels
  • 13,346
  • 11
  • 50
  • 114
Milan Vadgama
  • 221
  • 3
  • 7
1

Calculate string size that fits in UITextView:

 [yourString sizeWithFont:yourtxtView.font
              constrainedToSize:CGSizeMake(yourtxtView.frame.size.width,1000)
                  lineBreakMode:UILineBreakModeWordWrap];

Change frame of UITextView

 yourtxtView.frame  = CGRectMake(yourtxtView.frame.origin.x,yourtxtView.frame.origin.y,yourtxtView.frame.size.width,yourtxtView.frame.size.height+20);
Paresh Navadiya
  • 37,381
  • 10
  • 77
  • 128