首先确保您的类采用 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()
}
}