在“应用”部分中,我们有一个搜索字段和模式窗口可与其他用户聊天(DJSemiModalViewController
)。因此,据我了解可以抬起键盘上方的模式窗口,我们有以下代码
func setKeyboard() {
NotificationCenter.default.addObserver(self, selector: #selector(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 keyboardFrame = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
if self.controller.view.frame.origin.y == 0 {
let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as! Double
UIView.animate(withDuration: duration) {
self.controller.view.frame.origin.y -= keyboardFrame.height - self.view.safeAreaInsets.bottom
}
}
}
}
@objc func keyboardWillHide(notification: NSNotification) {
if self.controller.view.frame.origin.y != 0 {
self.controller.view.frame.origin.y = 0
}
}
如果我们在其上方设置setKeyboard(),则此代码可以正常工作
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableFooterView = UIView()
prepareSearchBar()
prepareFRC()
setKeyboard()
但是,如果我们点击搜索字段,则该应用程序将在行if self.controller.view.frame.origin.y == 0 {
线程1:致命错误:在隐式展开一个可选值时意外发现nil
但是如果我们这样评论setKeyboard()
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableFooterView = UIView()
prepareSearchBar()
prepareFRC()
//setKeyboard()
该应用程序不会终止,但是键盘不会抬高模式窗口上方,并且将模式窗口隐藏在后面。
请帮助解决该问题。