首先确保您的类采用 UITextViewDelegate 协议,以便在文本发生如下变化时通知您:
class MyClass: UIViewContoller, UITextViewDelegate
接下来在你的类的某个地方定义这个变量,这样你就可以跟踪约束中的高度:
var textHeightConstraint: NSLayoutConstraint!
接下来添加以下约束并激活它:
self.textHeightConstraint = addtextview.heightAnchor.constraint(equalToConstant: 40)
self.textHeightConstraint.isActive = true
(如果您不在 viewDidLoad 中执行此操作,则需要将 textHeightConstraint 设为可选)
下一个订阅委托(如果尚未完成):
addTextView.delegate = self
添加重新计算高度约束的函数:
func adjustTextViewHeight() {
let fixedWidth = addtextview.frame.size.width
let newSize = addtextview.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
self.textHeightConstraint.constant = newSize.height
self.view.layoutIfNeeded()
}
接下来在创建约束后添加对该函数的调用以设置初始大小:
self.adjustTextViewHeight()
最后添加这个方法来调整文字的高度:
func textViewDidChange(_ textView: UITextView) {
self.adjustTextViewHeight()
}
以防万一,这里有一个 UIViewController 子类中的最小示例:
class ViewController: UIViewController, UITextViewDelegate {
@IBOutlet var textView: UITextView!
@IBOutlet var textHolder: UIView!
var textHeightConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
textView.leadingAnchor.constraint(equalTo: textHolder.leadingAnchor, constant: 8).isActive = true
textView.trailingAnchor.constraint(equalTo: textHolder.trailingAnchor, constant: -8).isActive = true
textView.topAnchor.constraint(equalTo: textHolder.topAnchor, constant: 8).isActive = true
textView.bottomAnchor.constraint(equalTo: textHolder.bottomAnchor, constant: -40).isActive = true
self.textHeightConstraint = textView.heightAnchor.constraint(equalToConstant: 40)
self.textHeightConstraint.isActive = true
self.adjustTextViewHeight()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textViewDidChange(_ textView: UITextView) {
self.adjustTextViewHeight()
}
func adjustTextViewHeight() {
let fixedWidth = textView.frame.size.width
let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
self.textHeightConstraint.constant = newSize.height
self.view.layoutIfNeeded()
}
}