Fork me on GitHub

html搜索,文中的关键字变色

The iphone app im writing displays an html page, i would like to add a search feature where the user can search for instances for the keyword and highlight them (like in firefox using ctrl+F)

what's the best way to do this? in objective-c? would this be even possible with javascript?

Please point me to the right direction

 

NSString *filePath = PATH_OF_HTML_FILE;
NSError *err = nil;
NSString *pageHTML = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&err];

if(err)
{
pageHTML = [NSString stringWithContentsOfFile:filePath encoding:NSASCIIStringEncoding error:&err];

}


if([searchTxtField.text length])
{
NSRange range1 = [pageHTML rangeOfString:searchTxtField.text options:NSCaseInsensitiveSearch];
if(range1.location != NSNotFound)
{
NSString *highlightedString = [pageHTML substringWithRange:range1];
pageHTML = [pageHTML stringByReplacingOccurrencesOfString:highlightedString withString:[NSString stringWithFormat:@"<span style=\"background-color:yellow; color:red;\">%@</span>",highlightedString] options:NSCaseInsensitiveSearch range:NSMakeRange(0, [pageHTML length]) ];
[webView loadHTMLString:pageHTML baseURL:[NSURL fileURLWithPath:filePath]];
}


}



posted on 2012-03-23 15:08  pengyingh  阅读(932)  评论(0)    收藏  举报

导航