工作中发现,在webView中,如果h5内容自己的container中引入了划动控件,再在控件中通过input标签调起键盘,会导致webView中的视图发生向上偏移,将navigationbar顶出屏幕,同时webView的contentSize超出可视区域。
针对以上情况,通过监听keyboard的变化事件,实时改变webView的frame可以解决该问题
增加对 键盘弹出/缩回 事件的监听
funcaddKeybaordObserve() {
NotificationCenter.default.addObserver(self, selector: #selector(containerResizingFor(showingKeyboardNoti:)), name:NSNotification.Name.UIKeyboardWillShow, object:nil)
NotificationCenter.default.addObserver(self, selector: #selector(containerResizingFor(hidingKeyBoardNoti:)), name:NSNotification.Name.UIKeyboardWillHide, object:nil)
}
添加监听到通知后的处理方法
@objc func containerResizingFor(showingKeyboardNoti: Notification) {
guard let info = showingKeybboardNoti.userInfo else { return }
let value = info[UIKeyboardFrameEndUserInfoKey] as! NSValue
let kbHeight = value.cgRectValue.height
self.webView.frame = CGSize(width: view.frame.width, height: view.frame.height - kbHeight)
webView.setNeedsLayout()
}
@objc func containerResizingFor(hidingKeyBoardNoti: Notification) {
self.webView.frame = view.frame
self.webView.setNeedsLayout()
}
这里有点地方需要存疑,修改WKWebView的scrollView.contentSize同样可以生效,但是效果有时会不稳定,存在闪动等问题,因此这里还是选择了修改WebView的frame
最后,还要记得在deinit方法里将观察者移除——
deinit {
NotificationCenter.default.removeObserer(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserer(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}