ios: WebView内高亮搜索

由于webview 加载的是网页 只能用js 进行页内查找  废话不说上代码

// 注入 JS 查找
    NSString *resPath = [[NSBundle mainBundle] resourcePath];
    static NSString *jsQuery = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        jsQuery = [NSString stringWithContentsOfFile:[resPath stringByAppendingPathComponent:@"js_plugins.js"] encoding:NSUTF8StringEncoding error:nil];
        
    });
    NSString *js = [NSString stringWithFormat:@"var highlightPlugin = document.getElementById('js_plugins'); \
                    if (highlightPlugin == undefined) { \
                    document.body.innerHTML += '<div id=\"js_plugins\"> \
                    <style type=\"text/css\"> \
                    .utaHighlight { background-color:yellow; } \
                    .selectSpan { background-color:yellow; color:red;} \
                    </style> \
                    </div>'; \
                    %@ \
                    }", jsQuery];
    
    [self stringByEvaluatingJavaScriptFromString:js];
    
    // 清除上次的高亮并设置当前关键字高亮
    [self stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"jQuery('body').removeHighlight().utaHighlight('%@');", str]];
    
    // 获取关键字数量
    NSString *count = [self stringByEvaluatingJavaScriptFromString:@"jQuery('.utaHighlight').length"];
    
    if ([count integerValue]>0) {
        [self focusToFindIndex:0];
    }
dispatch_once 用单例的话不用每调用一次都读取一次文件,后面就是一些调用一些js文件的方法。
可扩展上一个下一个,暂时没有实现。
其他具体文件方法可以看demo
http://pan.baidu.com/s/1eQAGNPC

v 14.10.31 更新:

增加扩展上一个和下一个,其实也很简单

既然要用到上一个、下一个,肯定要记录下当前的位置,总的数量

1.定义两个全局变量

static NSInteger sCount ;//总数量
static NSInteger sNumber  = 1;//当前位置(默认从1开始)

2.增加上一个 下一个方法

- (void)nextFindIndex
{
    if (sNumber>=sCount) {
        return;
    }
    [self focusToFindIndex:sNumber];
    sNumber ++ ;
}

- (void)lastFindIndex
{
    if (sNumber<=0) {
        return;
    }
    sNumber--;
    [self focusToFindIndex:sNumber];
}

 

3.到这里的,之前写focusToFindIndex 方法需要修改

- (void)focusToFindIndex:(NSInteger)findIndex
{
    NSString *js = [NSString stringWithFormat:@"scrollToFindIdx(%d);", findIndex];
    CGFloat offset = [[self stringByEvaluatingJavaScriptFromString:js] floatValue];
    
    CGFloat contentHeight = self.scrollView.contentSize.height;
    offset = MIN(offset, contentHeight-self.scrollView.bounds.size.height);
    [self.scrollView setContentOffset:CGPointMake(0, offset) animated:YES];
}

同样highlightAllOccurencesOfString 方法也需要修改,即给变量赋值

// 获取关键字数量
    NSString *count = [self stringByEvaluatingJavaScriptFromString:@"jQuery('.utaHighlight').length"];
    sCount = [count intValue];
    sNumber = 1;
    if ([count intValue]>0) {
        [self focusToFindIndex:0];
    }

4.完毕

 

posted @ 2014-10-10 00:07  折半  阅读(658)  评论(1编辑  收藏  举报