如何在uiwebview页面中查找文本并将其突出显示并使用swift转到文本在页面中的位置?

例如chrome查找文本:

search example

但是我改用警报视图:

my search example in my app !!!

最佳答案

这是快速代码:

1)将UIWebViewSearch.js文件添加到您的项目中

func highlightAllOccurencesOfString(str:String) -> Int {

    let path = Bundle.main.path(forResource: "UIWebViewSearch", ofType: "js")

    var jsCode = ""

    do{

        jsCode = try String(contentsOfFile: path!)

    }catch
    {
    // do something

    }

    self.newsWebView.stringByEvaluatingJavaScript(from: jsCode)

    let startSearch = "uiWebview_HighlightAllOccurencesOfString('\(str)')"

    self.newsWebView .stringByEvaluatingJavaScript(from: startSearch)

    let  result = self.newsWebView.stringByEvaluatingJavaScript(from: "uiWebview_SearchResultCount")

    return  Int(result!)!


}

func scrollTo(index:Int)  {

    self.newsWebView.stringByEvaluatingJavaScript(from: "uiWebview_ScrollTo('\(index)')")

}

func removeAllHighlights() {

self.newsWebView.stringByEvaluatingJavaScript(from: "uiWebview_RemoveAllHighlights()")

}

关于ios - 使用swift在Webview页面中查找文本?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38317747/

10-09 16:21