当用户执行点击并按住手势来选择单词,然后将手指向屏幕的顶部或底部边缘拖动时,页面会自动滚动以适应选择。
这是一个短片演示它 https://youtu.be/Fw4cqH4gt6Y
我想防止这种行为WKWebView
.
这是我到目前为止所尝试过的:
in a bridge.js
webview可以访问的文件:
var shouldAllowScrolling = true;
document.addEventListener('selectionchange', e => {
shouldAllowScrolling = getSelectedText().length === 0;
window.webkit.messageHandlers.selectionChangeHandler.postMessage(
{
shouldAllowScrolling: shouldAllowScrolling
});
console.log('allow scrolling = ', shouldAllowScrolling);
});
然后在一个WKScriptMessageHandler
执行:
public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage)
{
switch message.name
{
case "selectionChangeHandler":
let params = paramsDictionary(fromMessageBody: message.body)
let shouldEnableScrolling = params["shouldAllowScrolling"] as? Bool ?? true
cell?.webView.scrollView.isScrollEnabled = shouldEnableScrolling
cell?.webView.scrollView.isUserInteractionEnabled = shouldEnableScrolling // not together with the line above
default:
fatalError("\(#function): received undefined message handler name: \(message.name)")
}
}
同样,我尝试致电preventDefault()
直接在 javascript 文件中处理一系列事件的函数,即scroll
and touchmove
,像这样:
document.addEventListener('touchmove', e => {
if (!shouldAllowScrolling) {
e.preventDefault()
}
}, {passive: false});
当选择某些文本时,这两种方法都可以成功防止滚动,但不会覆盖我的问题顶部描述的行为。
我可以接受 Swift 和 JavaScript 或两者混合的解决方案。