我在这个问题上花了几天时间,但没有看到解决方案。
我有一个inputAccessoryView
其中包括一个UIView
含有一个textView
和两个按钮。的行为inputAccessoryView
符合预期,并且在除一种情况外的所有情况下都工作正常。
当textView的高度增加时,我试图增加textView的高度inputAccessoryView
相同的数量。当我重新定义高度时inputAccessoryView
in textViewDidChange
, the inputAccessoryView
向下而不是向上增加键盘上方的高度。
我尝试了很多不同的建议,但没有任何效果。我猜是自动添加的NSLayoutConstraint
of the inputAccessoryView
但我不知道如何在 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
}
adding
inputAccessoryView.setTranslatesAutoresizingMaskIntoConstraints(true)
上面的代码有帮助,并且 inputAccessoryView 高度正确地向上增加,但是我无法同时满足多个约束的约束,并且很难识别违规者。另外,我得到了一个奇怪的效果,即 textView 在新行的每个第二个实例下面创建额外的空间。
thanks.
要使输入附件视图垂直增长,您只需设置其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()
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)