WKWebView如何在显示键盘时禁用adjustedContentInset



如果我在显示WKWebView时打开键盘,它会自动将adjustedContentInset添加到ScrollView中。但问题是,如果我自己处理键盘,它仍然会添加经过调整的ContentInset。我该怎么解决这个问题?

如果从WKWebView中删除处理键盘的观察器,它将停止添加adjustedContentInset:

NotificationCenter.default.removeObserver(self.webView, name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
NotificationCenter.default.removeObserver(self.webView, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self.webView, name: UIResponder.keyboardWillHideNotification, object: nil)

keyboardWillShowNotification/keyboardWillHideNotification触发时,我在更改web视图上的自动布局约束时遇到了这个问题。

对我有用的东西:

  1. 在添加键盘事件上的观察员后实例化WKWebView
  2. 更改自动布局约束后,触发布局阶段
let notificationCenter = NotificationCenter.default
notificationCenter.publisher(for: UIResponder.keyboardWillShowNotification, object: nil)
.sink { [weak self] _ in
self?.attachWebViewToKeyboard()
self?.view.layoutIfNeeded()
}
.store(in: &cancellables)
notificationCenter.publisher(for: UIResponder.keyboardWillHideNotification, object: nil)
.sink { [weak self] _ in
self?.attachWebViewToBounds()
self?.view.layoutIfNeeded()
}
.store(in: &cancellables)
webView = WKWebView(frame: .zero)

(我在这里使用Combine,但经典的addObserver也可以。(

向上投票的解决方案也有效,但缺点是当<input>元素获得焦点并打开键盘时,它也会禁用自动滚动内容偏移调整。

相关内容

  • 没有找到相关文章