Ios 快速调整约束以允许使用键盘
我是一个新的敏捷程序员,我的业余爱好是学习编码。我几乎完成了我的第一个应用程序,有一个tableview,其中单元格的一部分包含一个文本字段,用户可以编辑其中包含的数据 当用户在文本字段中单击时,键盘会弹出并遮挡大部分的tableview 我已经对此进行了研究,并且在过去的一个小时里一直在研究解决方案领域,但是我有点被困在从哪里开始的问题上。正如我所能说的,我应该调整tableview上的约束,使它不是从视图底部开始的0,而是它到底有多少像素,这就是键盘的高度 因此,我理解这个概念,但不知道如何执行这两大部分:Ios 快速调整约束以允许使用键盘,ios,swift,keyboard,tableview,Ios,Swift,Keyboard,Tableview,我是一个新的敏捷程序员,我的业余爱好是学习编码。我几乎完成了我的第一个应用程序,有一个tableview,其中单元格的一部分包含一个文本字段,用户可以编辑其中包含的数据 当用户在文本字段中单击时,键盘会弹出并遮挡大部分的tableview 我已经对此进行了研究,并且在过去的一个小时里一直在研究解决方案领域,但是我有点被困在从哪里开始的问题上。正如我所能说的,我应该调整tableview上的约束,使它不是从视图底部开始的0,而是它到底有多少像素,这就是键盘的高度 因此,我理解这个概念,但不知道如何
您需要在viewDidLoad中附加一些观察者:
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange), name: UIResponder.keyboardWillHideNotification, object: nil)
请记住在ViewWill中删除它们:
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
您需要一个@objc函数,以便您的观察者调用:
@objc private func keyboardWillChange(_ notification: Notification) {
guard let userInfo = (notification as Notification).userInfo, let value = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else {
return
}
if ((userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue) != nil {
let isKeyboardShowing = notification.name == UIResponder.keyboardWillShowNotification
var newHeight: CGFloat
let textHeight = inputTextView.textContainer.size.height
if isKeyboardShowing {
newHeight = value.cgRectValue.height - view.safeAreaInsets.bottom
bottomConstraint.constant = newHeight + textHeight
view.bringSubviewToFront(messageInputContainerView)
UIView.animate(withDuration: 0, delay: 0,
options: .curveEaseOut,
animations: { self.view.layoutIfNeeded() },
completion: nil)
}
else {
view.bringSubviewToFront(messageInputContainerView)
newHeight = value.cgRectValue.height - view.safeAreaInsets.bottom
bottomConstraint?.constant = view.safeAreaInsets.bottom + messageInputContainerView.bounds.height - textHeight
UIView.animate(withDuration: 0,
delay: 0,
options: .curveEaseOut,
animations: { self.view.layoutIfNeeded() },
completion: nil)
}
}
}
bottomConstraint
在本例中是您的类引用,附加到故事板上tableView的底部,是打开和关闭键盘时可移动的基线。您需要根据自己的用例/大小调整值和约束选择messageInputContainerView
是本例中我们的InputExtView
的容器。哇,这太棒了。非常感谢@LinusBicker不客气,请务必接受正确的答案:)您能再解释一下messageInputContainerView吗?我对此感到困惑,不知道如何使我的代码适应这一部分。@LinusBicker messageInputContainerView是一个UIView,它包含InputExtView,而InputExtView是一个UIExtView。在我的用例中,messageInputContainerView中也有一个send按钮,因此它通过将约束附加到父视图,一次将所有内容向上移动。我没有意识到我必须向约束添加一个iboutlet,从而创建bottomConstraint变量。非常感谢你!!!