3

我有一个 textView 可以插入不同长度的不同文本,有些短,有些长.​​. UITextView 是滚动视图的子视图。如何根据输入文本的长度动态设置 UITextView 的高度?

ViewDidLoad 中的这段代码不起作用:

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

4 回答 4

3

这不起作用,因为您的约束是 TextView 的当前 contentSize。你应该把你想要的最大尺寸。

例如,您的代码可能是这样的:

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

希望这可以帮助

于 2012-10-30T08:20:26.830 回答
2

由于 UITextView 是 UIScrollView 的子类,因此这可能会有所帮助:

UITextView *textView = [UITextView new];
textView.text = @"Your texts ......";
CGSize contentSize = textView.contentSize ;
CGRect frame = textView.frame ;
frame.size.height = contentSize.height ;
textView.frame = frame ;
于 2013-07-03T11:39:05.543 回答
2

下面的编码正在工作。请尝试一下

// 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;
于 2015-10-23T08:46:18.990 回答
1

Calculate string sizefitsUITextView:_

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

Change frameUITextView

 yourtxtView.frame  = CGRectMake(yourtxtView.frame.origin.x,yourtxtView.frame.origin.y,yourtxtView.frame.size.width,yourtxtView.frame.size.height+20);
于 2012-10-30T08:22:16.837 回答