【问题标题】:UITextView with dynamically height具有动态高度的 UITextView
【发布时间】:2012-10-19 13:21:38
【问题描述】:
我有一个 textView 可以插入不同长度的不同文本,有些短,有些长.. UITextView 是 scrollView 的子视图。如何根据输入文本的长度动态设置 UITextView 的高度?
ViewDidLoad 中的这段代码不起作用:
self.textView.contentSize = [self.textView.text sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(100, self.textView.contentSize.height) lineBreakMode:UIViewAutoresizingFlexibleHeight];
【问题讨论】:
标签:
ios
height
uitextview
frame
【解决方案1】:
这不起作用,因为您的约束是 TextView 的当前 contentSize。你应该放你想要的最大尺寸。
例如你的代码可能是这样的:
#define kMaxHeight 100.f
self.textView.contentSize = [self.textView.text sizeWithFont:[UIFont systemFontOfSize:14]
constrainedToSize:CGSizeMake(100, kMaxHeight)
lineBreakMode:UIViewAutoresizingFlexibleHeight];
希望对你有帮助
【解决方案2】:
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);
【解决方案3】:
由于 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 ;
【解决方案4】:
下面的代码正在运行。请尝试一下
// 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;