我有一个 KeyboardContainer 类(UIView 的子类/以编程方式创建,因此没有故事板),包括一个 UITextView,供用户在其中键入消息。它在聊天日志类中使用,并设置为 inputAccessoryView。我想在用户打字时动态更改它的高度。
我寻找答案并找到了一些。然而,我没有得到其中的大部分,因为它们对我不起作用。
我必须实施什么才能达到我想要的效果?
感谢您的帮助!
EDIT:
首先感谢您的帮助!
然而,我对编码还很陌生,所以我无法解决这个问题。我想这与我创建 KeyboardContainer 类及其约束的方式有关......
这是我的键盘容器类中的相关代码:
let textField:UITextView = {
let view = UITextView()
view.translatesAutoresizingMaskIntoConstraints = false
view.layer.cornerRadius = 15
view.layer.masksToBounds = true
view.font = UIFont.systemFont(ofSize: 15)
view.backgroundColor = .white
return view
}()
overried init(frame: CGRect){
super.init(frame: frame)
addSubview(textField)
textField.leftAnchor.constraint(equalTo: leftButton, constant: 5).isActive = true
textField.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
textFieldHeightAnchor = textField.heightAnchor.constraint(equalTo: heightAnchor, constant: -10)
textFieldHeightAnchor.isActive = true
textFieldRightAnchor = textField.rightAnchor.constraint(equalTo: rightAnchor, constant: -85)
textFieldRightAnchor.isActive = true
}
在我的聊天日志中我正在使用这个:
lazy var keyboard: KeyboardContainer = {
let key = KeyboardContainer()
key.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: 45)
key.sendButton.addTarget(self, action: #selector(handleSend), for: .touchUpInside)
return key
}()
override var inputAccessoryView: UIView?{
get{
return keyboard
}
}
我需要改变什么?我猜有限制吗?
您可以使您的 textView 符合 UITextViewDelegate,然后将其大小调整为它的 contentSize。
让你的视图控制器符合委托
class ViewController: UIViewController, **UITextViewDelegate** { ...
在那之后
yourTextView.delegate = self // put that in viewDidLoad()
然后你可以实现textViewDidChange方法。这意味着,每次您在键盘中输入内容时,都会调用此函数。
func textViewDidChange(_ textView: UITextView) {
if textView == youTextView {
let currentHeight = textView.frame.size.height
textView.frame.size.height = 0 // you have to do that because if not it's not working with the proper content size
textView.frame.size = textView.contentSize // here you detext your textView's content size and make it resize.
let newHeight = textView.frame.size.height
let heightDifference = newHeight - currentHeight // get the height difference from before and after editing
yourContainerView.frame.size.height += heightDifference
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)