【问题标题】:iOS WKWebView findString not selecting and scrollingiOS WKWebView findString 不选择和滚动
【发布时间】:2020-10-04 10:50:26
【问题描述】:

由于iOS 14 WebKit 支持findString,但还没有任何文档。

但是在 WWDC Sessions Discover WKWebView enhancements 他们提到这是“在页面上查找”的基本功能,您可以在其中找到一个字符串,WebView 将选择它并滚动到中心。

当我得到matchFound true 的结果时,它似乎很容易使用并且可以找到字符串,但是没有选择,也没有滚动。也许我错过了什么?

这是我尝试过的代码:

let webView = WKWebView()
    
// ...
// after loading a website with the desired string on it.
// ...
    
webView.find("hello world") { result in
    print(result.matchFound) // true
}

【问题讨论】:

  • 我还发现在webView.find("hello world") 之前调用webView.select(nil) 可以启用选择,但仍然不能滚动。

标签: ios swift webkit wkwebview


【解决方案1】:

到目前为止,我只能结合一点 JavaScript 让它“工作起来”。

let webView = WKWebView()
webView.select(nil)
webView.find("hello world") { result in
    guard result.matchFound else { return }
    webView.evaluateJavaScript(
        "window.getSelection().getRangeAt(0).getBoundingClientRect().top") { offset, _ in
        guard let offset = offset as? CGFloat else { return }
        webView.scrollView.scrollRectToVisible(
            .init(x: 0,
                  y: offset + webView.scrollView.contentOffset.y,
                  width: 100,
                  height: 100), animated: true)
    }
}

说明:

1。 webView.select(nil) 使其成为第一响应者。 这很重要,否则当找到匹配项时,它不会被选中。

2。 webView.find("my string")

3。 如果找到匹配项,则使用 JavaScript 获取所选文本的偏移量。

4。 当接收到偏移量滚动到它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-23
    • 1970-01-01
    • 1970-01-01
    • 2019-12-25
    • 2020-01-05
    • 1970-01-01
    • 1970-01-01
    • 2016-11-20
    相关资源
    最近更新 更多