To customize the appearance of links on a webpage, you can utilize basic CSS rules. For instance, to eliminate the underline and change the color of a link to red, you can apply the following CSS style:
a {
text-decoration: none;
color: red;
}
When dealing with a UIWebView
, there are specific styles that can be modified using non-standard CSS properties. A comprehensive list of these properties can be found here.
If you need to implement this style on an HTML page that you do not have control over, you will need to inject JavaScript code into the target page from your native Objective-C code.
Firstly, let's create the JavaScript code that changes the style of an <a>
element with the id
"urlID":
var link = window.document.getElementById('urlId');
link.style['text-decoration'] = 'none';
link.style.color = 'red';
Next, instruct the native UIWebView
to run this JavaScript code when the web page finishes loading (ensuring that the DOM elements we are targeting exist). This can be achieved by utilizing the UIWebView UIWebViewDelegate
protocol along with its method webViewDidFinishLoad:
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSString *javaScriptCodeToExecute = @"var link = window.document.getElementById('urlId'); link.style['text-decoration'] = 'none'; link.style.color = 'red';";
[_webView stringByEvaluatingJavaScriptFromString:javaScriptCodeToExecute];
}
The JavaScript code is stored in the string variable javaScriptCodeToExecute
, and the UIWebView
is instructed to execute it using the stringByEvaluatingJavaScriptFromString:
method.