作者:A布匹rray | 来源:互联网 | 2023-01-02 12:14
我有这个UITextView&我希望它的高度在用户输入时动态改变.我想以编程方式进行.我在另一个UIView上面有UITextView.约束设置如下:
addtextview.leadingAnchor.constraint(equalTo: addtasktextview.leadingAnchor, constant: 8).isActive = true
addtextview.trailingAnchor.constraint(equalTo: addtasktextview.trailingAnchor, constant: -8).isActive = true
addtextview.topAnchor.constraint(equalTo: addtasktextview.topAnchor, constant: 8).isActive = true
addtextview.bottomAnchor.constraint(equalTo: addtasktextview.bottomAnchor, constant: -40).isActive = true
有趣的是,我也在tableViewCells中使用textview并使用这种约束方法动态地改变高度,但是在这里它不起作用.我希望textview的高度以向上移动的方式增加.因此,当新线开始时,顶部应移动以保持下面的间距.
我该怎么做?帮助将不胜感激.
更新:我能够使用下面的@ upholder-of-truth的答案.我还能够通过查找textview normal height和newSize.height之间的差异,然后将该差异添加到容器的高度来动态更改父UIView容器高度.
1> Upholder Of ..:
首先确保您的类采用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()
}
}