我正在开发一个聊天应用程序,我试图让用户以交互方式关闭键盘。不幸的是,它没有像我预期的那样工作:
(这是我开始拉下键盘的时候。我希望我的 TextView 无论如何都留在键盘的顶部。这是我尝试过的:
在viewDidLoad
中:
textView.keyboardDismissMode = .interactive//I have tried the same thing with the table view as well, but it produces the same result.
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
在同一个类(class):
func keyboardWillShow(_ aNotification: NSNotification) {
let info = aNotification.userInfo!
let keyboardFrame = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue()
UIView.animate(withDuration: 0.25) { () -> Void in
self.messageBottomConstraint.constant = keyboardFrame.height
self.view.layoutIfNeeded()
}
}
func keyboardWillHide(_ aNotification: NSNotification) {
UIView.animate(withDuration: 0.25) { () -> Void in
self.messageBottomConstraint.constant = 0
self.view.layoutIfNeeded()
}
}
如何在用户关闭时将 TextView 保持在键盘顶部?谢谢!
最佳答案
您应该覆盖 UIResponder
上的 inputAccessoryView
或 inputAccessoryViewController
属性(UIViewController
继承自)。这将允许您提供一个 View / View Controller ,当它出现时自动固定到键盘的顶部。
This blog post举例说明如何执行此操作。
关于ios - 关闭键盘的平滑过渡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38624638/