突出显示UIWebView中的文本

时间:2013-10-17 07:18:08

标签: javascript iphone ios objective-c uiwebview

我有UIWebView用于显示HTML页面文章。我需要搜索字符串或文本并突出显示。我提到了这份文件http://www.icab.de/blog/2010/01/12/search-and-highlight-text-in-uiwebview/。但什么都没发生。

 - (void)viewDidLoad
    {
   [wbCont loadHTMLString:webString baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];


    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    // getting an NSString
    NSString  *savedValue = [prefs stringForKey:@"got"];

    NSLog(@"saved is %@",savedValue);

    [self highlightAllOccurencesOfString:savedValue];

    [self.view addSubview:wbCont];

    [self.view setBackgroundColor:[UIColor grayColor]];


    }

   - (NSInteger)highlightAllOccurencesOfString:(NSString*)str
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"UIWebViewSearch" ofType:@"js"];
    NSString *jsCode = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

    [wbCont stringByEvaluatingJavaScriptFromString:jsCode];

    NSString *startSearch = [NSString stringWithFormat:@"window.onload = function (){uiWebview_HighlightAllOccurencesOfString('%@')}",str];
    [wbCont stringByEvaluatingJavaScriptFromString:startSearch];

    NSString *result = [wbCont stringByEvaluatingJavaScriptFromString:@"uiWebview_SearchResultCount"];
    return [result integerValue];
}

1 个答案:

答案 0 :(得分:2)

我将发布我是如何解决类似情况的。我使用搜索显示控制器在一个uitableview中搜索。取而代之的是UIWebView,我使用了Scott Kohler UIWebView search创建的以下子类。我希望这可以帮到你:

SearchWebView.h

#import <Foundation/Foundation.h>

@interface SearchWebView : UIWebView

- (NSInteger)highlightAllOccurencesOfString:(NSString*)str;
- (void)removeAllHighlights;

@end

SearchWebView.m

#import "SearchWebView.h"

@implementation SearchWebView

- (NSInteger)highlightAllOccurencesOfString:(NSString*)str
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"UIWebViewSearch" ofType:@"js"];
    NSString *jsCode = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

    [self stringByEvaluatingJavaScriptFromString:jsCode];

    NSString *startSearch = [NSString stringWithFormat:@"window.onload = function (){uiWebview_HighlightAllOccurencesOfString('%@')}",str];
    [self stringByEvaluatingJavaScriptFromString:startSearch];

    NSString *result = [self stringByEvaluatingJavaScriptFromString:@"uiWebview_SearchResultCount"];
    return [result integerValue];
}

- (void)removeAllHighlights
{
    [self stringByEvaluatingJavaScriptFromString:@"uiWebview_RemoveAllHighlights()"];
}

@end

javascript包含以下代码:

var uiWebview_SearchResultCount = 0;

function uiWebview_HighlightAllOccurencesOfStringForElement(element,keyword) {

    if (element) {
        if (element.nodeType == 3) {        // Text node
            while (true) {
            //if (counter < 1) {
            var value = element.nodeValue;  // Search for keyword in text node
            var idx = value.toLowerCase().indexOf(keyword);

            if (idx < 0) break;             // not found, abort

            //(value.split);

            //we create a SPAN element for every parts of matched keywords
            var span = document.createElement("span");
            var text = document.createTextNode(value.substr(idx,keyword.length));
            span.appendChild(text);

            span.setAttribute("class","uiWebviewHighlight");
            span.style.backgroundColor="yellow";
            span.style.color="black";

            uiWebview_SearchResultCount++;    // update the counter

            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;
            window.scrollTo(0,span.offsetTop);

        }
    } else if (element.nodeType == 1) { // Element node
        if (element.style.display != "none" && element.nodeName.toLowerCase() != 'select') {
            for (var i=element.childNodes.length-1; i>=0; i--) {
                uiWebview_HighlightAllOccurencesOfStringForElement(element.childNodes[i],keyword);
            }
        }
    }
}
}

// the main entry point to start the search
function uiWebview_HighlightAllOccurencesOfString(keyword) {

    uiWebview_RemoveAllHighlights();
    uiWebview_HighlightAllOccurencesOfStringForElement(document.body, keyword.toLowerCase());
}

// helper function, recursively removes the highlights in elements and their childs
function uiWebview_RemoveAllHighlightsForElement(element) {
if (element) {
    if (element.nodeType == 1) {
        if (element.getAttribute("class") == "uiWebviewHighlight") {
            var text = element.removeChild(element.firstChild);
            element.parentNode.insertBefore(text,element);
            element.parentNode.removeChild(element);
            return true;
        } else {
            var normalize = false;
            for (var i=element.childNodes.length-1; i>=0; i--) {
                if (uiWebview_RemoveAllHighlightsForElement(element.childNodes[i])) {
                    normalize = true;
                }
            }
            if (normalize) {
                element.normalize();
            }
        }
    }
}
return false;
}
// the main entry point to remove the highlights
function uiWebview_RemoveAllHighlights() {
    uiWebview_SearchResultCount = 0;
    uiWebview_RemoveAllHighlightsForElement(document.body);
}

cellForRowAtIndexPath中并总结:

MyModel *model;
if(isSearching) model = [filteredArray objectAtIndex:indexPath.row];
else model = [allItems objectAtIndex:indexPath.row];

SearchWebView *descripcion = (SearchWebView *)[cell viewWithTag:3];
descripcion.delegate = self;
descripcion.scrollView.scrollEnabled = NO;
descripcion.scrollView.bounces = NO;

[descripcion loadHTMLString:[NSString stringWithFormat:@"<html><head><title></title><style type=\"text/css\">img{float:rigth !important;}</style></head><body style=\"text-align:justify; font-family:Helvetica\"><p>%@</p></body></html>",[resultado itemDescr]] baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
if(isSearching)[descripcion highlightAllOccurencesOfString:[NSString stringWithFormat:@"%@",searchBar.text]];