滚动到UIWebView上的文本

Scroll to text on UIWebView

本文关键字:文本 UIWebView 滚动      更新时间:2023-09-26

我正在用最新的SDK和XCode 4.2开发一个iOS应用程序。

我想在UIWeb视图中搜索文本,然后滚动到找到的第一个文本。

我正在使用本教程查找文本:http://zaldzbugz.posterous.com/how-to-search-a-string-inside-uiwebview

如何滚动到找到的第一个文本?

让我们循序渐进。

突出显示

  1. 将在搜索的文本周围添加一个span元素。对于跨度,高亮显示颜色设置为跨度的背景。修改后的HTML字符串将在视图中呈现

您使用的代码包含以下代码段。

    var span = document.createElement("span");
        var text = document.createTextNode(value.substr(idx,keyword.length));
            span.appendChild(text);
            span.setAttribute("class","uiWebviewHighlight");
            span.style.backgroundColor="black";
            span.style.color="white";

我们需要一个id到跨度才能移动。所以添加id如下,

      var span = document.createElement("span");
        var text = document.createTextNode(value.substr(idx,keyword.length));
            span.appendChild(text);
            span.setAttribute("id","SEARCH WORD");
            span.setAttribute("class","uiWebviewHighlight");
            span.style.backgroundColor="black";
            span.style.color="white";

移动到第一次出现

在"Webview didload"中使用以下javascript移动到第一次出现。

[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementById('SEARCH WORD').scrollIntoView()];

希望这会有所帮助。

看看教程中用于突出显示的最后一条注释。http://zaldzbugz.posterous.com/how-to-search-a-string-inside-uiwebview

在使用span 进行所有操作后,将此代码块添加到UIWebViewSearch.js中

//old code
    text = document.createTextNode(value.substr(idx+keyword.length));
    element.deleteData(idx, value.length - idx);
    var next = element.nextSibling;
    element.parentNode.insertBefore(span, next);
    element.parentNode.insertBefore(text, next);
    element = text;
//new portion of code
    if (uiWebview_SearchResultCount == 1)
    {
       var desiredHeight = span.offsetTop - 140;
       window.scrollTo(0,desiredHeight);
    }

我已经在iPhone模拟器4.3和5.0上检查了这个解决方案。

您可以滚动到使用此修改找到的最顶部文本:

// >=1
if (uiWebview_SearchResultCount >= 1) 
{
    var desiredHeight = span.offsetTop - 140;
    window.scrollTo(0,desiredHeight);
}