【问题标题】:Adjusting height of UITextView to its text does not work properly将 UITextView 的高度调整为其文本无法正常工作
【发布时间】:2017-03-30 02:19:27
【问题描述】:

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

当我点击键盘上的输入键以添加新行时,大小会发生变化,但相对于第一行文本的上边距每隔一次会有所不同。


设置

  • 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 的高度,但他们只是采取了同样的做法。

【问题讨论】:

    标签: ios swift height uitextview


    【解决方案1】:

    要解决这个问题,继承 UITextView 并覆盖 setContentOffset 以仅在内容高度大于固有内容高度时才允许滚动。比如:

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

    对于自动增长的动态高度文本视图,插入符号在开始新行时移动。此时,文本视图的大小还没有增长到新的大小。文本视图试图通过滚动不必要的文本内容来使插入符号可见。

    您可能还需要覆盖 intrinsicContentSize。

    【讨论】:

    • 完美运行!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多