这对我来说起作用了,其他所有解决方案都没有。
func adjustUITextViewHeight(arg : UITextView) {
arg.translatesAutoresizingMaskIntoConstraints = true
arg.sizeToFit()
arg.scrollEnabled = false
}
在 Swift 4 中,arg.scrollEnabled = false
的语法已更改为 arg.isScrollEnabled = false
。
textField.scrollEnabled = false
应该就可以了。我所需要做的是:
这样可以使自动布局根据其内容动态调整textView的大小。
试一下这个:
CGRect frame = self.textView.frame;
frame.size.height = self.textView.contentSize.height;
self.textView.frame = frame;
编辑-这是Swift代码:
var frame = self.textView.frame
frame.size.height = self.textView.contentSize.height
self.textView.frame = frame
Swift 4
将其添加到您的类中
UITextViewDelegate
func textViewDidChange(_ textView: UITextView) {
let fixedWidth = textView.frame.size.width
textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
var newFrame = textView.frame
newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
textView.frame = newFrame
}
textView.translatesAutoresizingMaskIntoConstraints = true
也是必需的。 - Ryan在DeyaEldeen的回答之后。
对于我的情况,我通过添加
自动增加了文本视图的高度。
Swift 3
textView.translatesAutoresizingMaskIntoConstraints = false
textView.isScrollEnabled = false
Swift 5,使用扩展:
extension UITextView {
func adjustUITextViewHeight() {
self.translatesAutoresizingMaskIntoConstraints = true
self.sizeToFit()
self.isScrollEnabled = false
}
}
使用案例:
textView.adjustUITextViewHeight()
不用担心 storyboard 中 textView 的高度(一开始只需使用一个常量)
只需连接您的textView的高度约束即可。
@IBOutlet var textView: UITextView!
@IBOutlet var textViewHeightConstraint: NSLayoutConstraint!
textViewHeightConstraint.constant = self.textView.contentSize.height
textView
允许根据内容增高,则textView.isScrollEnabled = false
应该可以与自动布局一起正常工作。
如果您希望保持 textView
的可滚动性,则需要添加一个可选的高度约束,
internal lazy var textViewHeightConstraint: NSLayoutConstraint = {
let constraint = self.textView.heightAnchor.constraint(equalToConstant: 0)
constraint.priority = .defaultHigh
return constraint
}()
public override func layoutSubviews() {
super.layoutSubviews()
// Assuming there is width constraint setup on the textView.
let targetSize = CGSize(width: textView.frame.width, height: CGFloat(MAXFLOAT))
textViewHeightConstraint.constant = textView.sizeThatFits(targetSize).height
}
layoutSubviews()
的原因是确保textView在水平方向上正确布局,以便我们可以依赖宽度来计算高度。textView
的实际高度将小于contentSize
。并且textView将可滚动。我添加了这两行代码,对我很有效。
在Swift 5+中有效。
func adjustUITextViewHeight(textView : UITextView)
{
textView.translatesAutoresizingMaskIntoConstraints = true
textView.isScrollEnabled = false
textView.sizeToFit()
}