gpt4 book ai didi

ios - 将 UITextView 的高度调整为其文本无法正常工作

转载 作者:行者123 更新时间:2023-11-28 06:30:02 24 4
gpt4 key购买 nike

我编写了以下代码来使 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
}
}

enter image description here enter image description here

我尝试了其他几种方法来适应 UITextView 的高度,但它们的表现都是一样的。

最佳答案

要解决此问题,子类化 UITextView 并覆盖 setContentOffset 以仅在内容高度大于固有内容高度时才允许滚动。像这样的东西:

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

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

您可能还需要重写 intrinsicContentSize。

关于ios - 将 UITextView 的高度调整为其文本无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40622737/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com