具有动态高度的UITextView

时间:2012-10-30 08:13:53

标签: ios height uitextview frame

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

ViewDidLoad中的此代码无效:

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

4 个答案:

答案 0 :(得分:3)

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

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

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

希望这有帮助

答案 1 :(得分: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 ;

答案 2 :(得分: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;

答案 3 :(得分:1)

{p> Calculate string size fits UITextView中的 [yourString sizeWithFont:yourtxtView.font constrainedToSize:CGSizeMake(yourtxtView.frame.size.width,1000) lineBreakMode:UILineBreakModeWordWrap];

Change frame
UITextView

yourtxtView.frame = CGRectMake(yourtxtView.frame.origin.x,yourtxtView.frame.origin.y,yourtxtView.frame.size.width,yourtxtView.frame.size.height+20);

{{1}}