How to Change Text Selection Color in UIwebview iOS

Is it possible to change text selection color in UIWebview ios?

Yes. I wasted 2 days to resolve this headache issue.Visit This Link and Place JS Code in your JS File.Import it in .HTML file.

Here's the sample code for it.

function highlight(colour) {
var range, sel;
if (window.getSelection) {
// IE9 and non-IE
try {
if (!document.execCommand("BackColor", false, colour)) {
makeEditableAndHighlight(colour);
}
} catch (ex) {
makeEditableAndHighlight(colour)
}
} else if (document.selection && document.selection.createRange) {
// IE <= 8 case
range = document.selection.createRange();
range.execCommand("BackColor", false, colour);
}}

call this method by Objective-C code

[webView stringByEvaluatingJavaScriptFromString:@"highlight('#ff0')"];

How to change the text selection color in WKWebView?

As of iOS 13, setting WKWebView's tintColor property also changes the selection color (and the caret color).

WKWebView *webView = ...
webView.tintColor = UIColor.redColor;

Extra tip: if you have an app that has dark mode support but for some reason the WKWebView content must be light mode, you can either force the whole view controller containing the WKWebView to have the light mode trait or you can do:

if (@available(iOS 13.0, *)) {
webView.tintColor = [webView.tintColor resolvedColorWithTraitCollection:[UITraitCollection traitCollectionWithUserInterfaceStyle:UIUserInterfaceStyleLight]];
}

this ensures that the selection and caret colors will be visible with "light" content in the html

how to change the text color in uiwebview in iphone

[self.itemSummary loadHTMLString:[NSString stringWithFormat:@"<html><body bgcolor=\"#000000\" text=\"#FFFFFF\" face=\"Bookman Old Style, Book Antiqua, Garamond\" size=\"5\">%@</body></html>", [item objectForKey:@"description"]] baseURL: nil];

You can use HTML colors.


Edit: added the text color.


Edit 2: added font size and face

How to highlight or change color of text within iOS?

In iOS 6 you can do it, because iOS 6 now allows UITextView (as well as UILabel, UIButton etc.) to display styled text (NSAttributedString). You color the word with NSForegroundColorAttributeName and color its background with NSBackgroundColorAttributeName and presto, there's your highlight. There are several very good WWDC 2012 videos on this topic.

UIWebView caret color with setTintColor?

Setting the Tint color for UIWebview will not work for text highlighting. All you can do is set the background color of that text and then remove it by using javascript.
Here's the Link having the Best solution to this problem.

highlight text in UIWebView

I will post how i solved a similar situation. I used a search display controller to search in one uitableview. Instead UIWebView, i used the following subclass created by Scott Kohler UIWebView search. I hope this could help you:

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

The javascript contains the following code:

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);
}

In cellForRowAtIndexPath and summarizing:

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]];

Control text selection behavior in iOS Mobile Safari and/or UIWebView?

iOS 8's WKWebView might be able to solve this problem. WKWebViewConfiguration has a property called selectionGranularity. The comment reads:

The level of granularity with which the user can interactively select
content in the web view. Possible values are described in
WKSelectionGranularity. The default value is
WKSelectionGranularityDynamic.

One of the two possible values is WKSelectionGranularityCharacter. The comment says:

Selection endpoints can be placed at any character boundary.

I have not tried it yet, but it sounds very promising!

Update 7/6/15: It looks like it's not that easy: Text Selection in WKWebView: WKSelectionGranularityCharacter

Update 7/10/15: When you closely investigate the iOS Kindle app, you can see that they have re-implemented "native" text selection in JavaScript because they couldn't make native text selection behave the way they wanted to. I'm pretty sure they must have tried everything else before they decided to re-implement it.



Related Topics



Leave a reply



Submit