将UITextView的高度调整为其文本无法正常工作 [英] Adjusting height of UITextView to its text does not work properly

查看:170
本文介绍了将UITextView的高度调整为其文本无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下代码以使UITextView的高度适合其文本.

I wrote following code to fit UITextView's height to its text.

大小发生变化,但是当我点击键盘上的Enter键以添加新行时,相对于文本第一行的上边距有所不同.

The size changes but top margin relative to first line of text differ every other time when I tap enter key on keyboard to add new line.

  • xCode 7.3
  • 部署目标:iOS 9
import UIKit

class ViewController: UIViewController, UITextViewDelegate {

    lazy var textView: UITextView = {
        let tv = UITextView(frame: CGRectMake(20, 200, (self.view.frame.width - 40), 0) )
        tv.backgroundColor = UIColor.lightGrayColor()
        return tv
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addSubview( textView )
        
        textView.delegate = self
        let height = self.height(textView)
        let frame = CGRectMake(textView.frame.origin.x, textView.frame.origin.y, textView.frame.width, height)
        textView.frame = frame
    }

    
    func textViewDidChange(textView: UITextView) {
        
        let frame = CGRect(x: textView.frame.origin.x, y: textView.frame.origin.y, width: textView.frame.width, height: height(textView) )
        textView.frame = frame
    }


    func height(textView: UITextView) -> CGFloat {
        let size = CGSizeMake(textView.frame.size.width, CGFloat.max)
        let height = textView.sizeThatFits(size).height
        return height
    }
}

我尝试了其他几种方法来适应UITextView的高度,但它们的作用相同.

I tried few other ways to fit UITextView height but they just acted the same say.

推荐答案

要解决此问题,请子类UITextView并重写setContentOffset以仅在内容高度大于固有内容高度时才允许滚动.像这样:

To fix this, subclass UITextView and override setContentOffset to allow scrolling only if the content height is larger than the intrinsic content height. Something like:

override func setContentOffset(_ contentOffset: CGPoint, animated: Bool) {
    let allowScrolling = (contentSize.height > intrinsicContentSize.height)
    if allowScrolling {
        super.setContentOffset(contentOffset, animated: animated)
    }
}

对于自动增长的动态高度文本视图,插入符号会在开始新行时移动.目前,文本视图的大小尚未增长到新的大小.文本视图通过滚动不必要的文本内容来尝试使插入符号可见.

For auto-growing dynamic height text view, the caret moves on starting a new line. At this moment, the size of the text view hasn't grown to the new size yet. The text view tries to make the caret visible by scrolling the text content which is unnecessary.

您可能还需要覆盖internalContentSize.

You may also need to override intrinsicContentSize too.

这篇关于将UITextView的高度调整为其文本无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆