问题描述
我正在使用以下功能,每当键盘出现时,它就会更改Y轴。另一个功能是,如果您在视图上点击任意位置,键盘就会消失,并且框架应回到其原始位置。
我正在使用Firestore,因此当我启动该应用程序时,我正在使用Firestore Auth来检查用户是否已登录(如果用户未登录登录页面),一旦登录,便会显示关闭后,您将回到根控制器,将看到一个选项卡,其中包含三个选项卡,每个选项卡连接到单独的视图控制器,每个选项卡都放入导航控制器。
第一个标签向您显示一个视图控制器,其中的表格视图显示了我所有的联系人, 然后,我点击一个单元格,该单元格将我带到消息视图控制器,可以在其中发送和接收消息。
在我的邮件viewWillAppear中的视图控制器中,我将选项卡栏isHidden设置为true,然后将UITextView设置为视图控制器的底部
应该发生的事情是,一旦点击UITextView,UITextView应该随着键盘的出现而向上移动,
我使用相同的功能,但是发生的是键盘出现并覆盖了UITextView,
然后,当我点击主视图以关闭键盘时,键盘消失了,但是框架向上移动,但是它没有向上移动一定距离,这是没有意义的,因为它没有向上移动到应有的位置那时我一直在想,也许它正在上升到标签栏的高度,但没有这样做,它介于两者之间
让我很难理解的是,我还尝试过,当您点击联系单元时,而不是将消息视图控制器推到我使用的导航堆栈上,当我这样做时,它会很好地工作,但是我会非常喜欢消息控制器位于导航堆栈中,因此我可以轻松地向后移动
任何反馈将不胜感激
func keyboardNotifications() {
NotificationCenter.default.addobserver(self,selector: #selector(self.keyboardWillShow),name: UIResponder.keyboardWillShowNotification,object: nil)
NotificationCenter.default.addobserver(self,selector: #selector(keyboardWillHide),name: UIResponder.keyboardWillHideNotification,object: nil)
}
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y == 0 {
self.view.frame.origin.y -= keyboardSize.height
}
}
}
@objc func keyboardWillHide(notification: NSNotification) {
if self.view.frame.origin.y != 0 {
self.view.frame.origin.y = 0
}
}
解决方法
您可以使用以下代码。
注意:bottomConstraint
是包含textview的视图的底部约束
override func viewDidLoad() {
super.viewDidLoad()
.
.
.
NotificationCenter.default.addObserver(self,selector: #selector(keyboardWillShow),name: UIResponder.keyboardWillShowNotification,object: nil)
NotificationCenter.default.addObserver(self,selector: #selector(keyboardWillHide),name: UIResponder.keyboardWillHideNotification,selector: #selector(keyboardWillChangeFrame),name: UIResponder.keyboardWillChangeFrameNotification,object: nil)
}
@objc func keyboardWillShow(_ notification:Notification) {
adjustingHeight(true,notification: notification)
}
@objc func keyboardWillHide(_ notification:Notification) {
adjustingHeight(false,notification: notification)
}
@objc func keyboardWillChangeFrame(_ notification: Notification) {
adjustingHeight(false,notification: notification)
}
func adjustingHeight(_ show:Bool,notification:Notification) {
var userInfo = (notification as NSNotification).userInfo!
let keyboardFrame:CGRect = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let animationDurarion = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as! TimeInterval
let changeInHeight = (keyboardFrame.height ) * (show ? 1 : 0)
self.bottomConstraint.constant = changeInHeight
UIView.animate(withDuration: animationDurarion,animations: { () -> Void in
self.view.layoutIfNeeded()
})
}