UITextView作為內(nèi)容文本輸入?yún)^(qū)域,有的時(shí)候我們需要根據(jù)內(nèi)容動(dòng)態(tài)改變文本區(qū)域的高度,效果如下:

定義UITextView,實(shí)現(xiàn)UITextViewDelegate:
-(UITextView *)textView{
if (!_textView) {
_textView=[[UITextView alloc]initWithFrame:CGRectMake(30, 200, CGRectGetWidth([[UIScreen mainScreen] bounds])-60, 30)];
[_textView setTextColor:[UIColor redColor]];
[_textView.layer setBorderColor:[[UIColor blackColor] CGColor]];
[_textView setFont:[UIFont systemFontOfSize:15]];
[_textView.layer setBorderWidth:1.0f];
[_textView setDelegate:self];
}
return _textView;
}
實(shí)現(xiàn)textViewDidChange方法:
-(void)textViewDidChange:(UITextView *)textView{
static CGFloat maxHeight =60.0f;
CGRect frame = textView.frame;
CGSize constraintSize = CGSizeMake(frame.size.width, MAXFLOAT);
CGSize size = [textView sizeThatFits:constraintSize];
if (size.height<=frame.size.height) {
size.height=frame.size.height;
}else{
if (size.height >= maxHeight)
{
size.height = maxHeight;
textView.scrollEnabled = YES; // 允許滾動(dòng)
}
else
{
textView.scrollEnabled = NO; // 不允許滾動(dòng)
}
}
textView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, size.height);
}