简体   繁体   中英

UITextView with dynamically height

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];

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

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 ;

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;

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM