我已经在这个问题上花了几天的时间,但看不到解决方案。
我有一个inputAccessoryView,它由一个包含一个textView和两个按钮的UIView组成。inputAccessoryView的行为符合预期,并且在除一种情况之外的所有情况下都工作正常。
当textView的高度增加时,我会尝试将inputAccessoryView的高度增加相同的量。当我在textViewDidChange中重新定义inputAccessoryView的高度时,inputAccessoryView在键盘上向下而不是向上增加高度。
我尝试了许多不同的建议,但都没有奏效。我猜是inputAccessoryView自动添加的NSLayoutConstraint,但我不知道如何在swift和iOS 8.3中更改该值。
func textViewDidChange(textView: UITextView) {
var contentSize = messageTextView.sizeThatFits(CGSizeMake(messageTextView.frame.size.width, CGFloat.max))
inputAccessoryView.frame.size.height = contentSize.height + 16
}添加
inputAccessoryView.setTranslatesAutoresizingMaskIntoConstraints(true)对上面的代码有帮助,inputAccessoryView高度正确地向上增加,但是我无法同时满足几个约束的约束,并且很难识别违规者。我还得到了一个奇怪的效果,textView会在下面每隔一次新行的实例上创建额外的空间。
谢谢。
发布于 2015-09-18 17:08:23
要让输入附件视图垂直增长,你只需设置它的autoresizingMask = .flexibleHeight,计算它的intrinsicContentSize,然后让框架来做剩下的事情。
代码:
class InputAccessoryView: UIView, UITextViewDelegate {
let textView = UITextView()
override init(frame: CGRect) {
super.init(frame: frame)
// This is required to make the view grow vertically
self.autoresizingMask = UIView.AutoresizingMask.flexibleHeight
// Setup textView as needed
self.addSubview(self.textView)
self.textView.translatesAutoresizingMaskIntoConstraints = false
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[textView]|", options: [], metrics: nil, views: ["textView": self.textView]))
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[textView]|", options: [], metrics: nil, views: ["textView": self.textView]))
self.textView.delegate = self
// Disabling textView scrolling prevents some undesired effects,
// like incorrect contentOffset when adding new line,
// and makes the textView behave similar to Apple's Messages app
self.textView.isScrollEnabled = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var intrinsicContentSize: CGSize {
// Calculate intrinsicContentSize that will fit all the text
let textSize = self.textView.sizeThatFits(CGSize(width: self.textView.bounds.width, height: CGFloat.greatestFiniteMagnitude))
return CGSize(width: self.bounds.width, height: textSize.height)
}
// MARK: UITextViewDelegate
func textViewDidChange(_ textView: UITextView) {
// Re-calculate intrinsicContentSize when text changes
self.invalidateIntrinsicContentSize()
}
}发布于 2020-03-15 07:33:52
快进到2020年,您只需执行以下操作,其他所有操作都与maxkonovalov的答案相同
override var intrinsicContentSize: CGSize {
return .zero
}
// MARK: UITextViewDelegate
func textViewDidChange(_ textView: UITextView) {
sizeToFit()
}https://stackoverflow.com/questions/31822504
复制相似问题