UITextView 动态高度

UITextView的动态高度,取决于输入字符的变化,因此我们可以在

 - (void)textViewDidChange:(UITextView *)textView;

方法里处理该业务逻辑;
在实际编码的过程中,有两种情况考虑:

  • 使用autoLayout
    首先,我们需要将UITextView的scrollEnabled 设置为 NO,这样是为了解决文字换行的时候,文字整体上移然后回落这种不友好的体验。
CGSize textViewSize = [textView sizeThatFits:CGSizeMake(textView.frame.size.width, MAXFLOAT)];
self.heightConstraint.constant = textViewSize.height;
// 这里的heightConstraint 是高度的约束
  • 不使用autoLayout
// 直接更新contentSize Height
CGRect frame = textView.frame;
frame.size.height = textView.contentSize.height;
textView.frame = frame;

你可能感兴趣的:(UITextView 动态高度)