DEV Community

Ceri-anne
Ceri-anne

Posted on

Dynamically adding CSS to webviews in Swift

This article was first published here https://www.ceri-anne.co.uk/dynamically-add-css-to-webviews-in-swift

This week, I needed to figure out how to dynamically add css to a webView in iOS and it was much easier than I thought it would be.

All you need to do is make use of the webViewdidFinish function in the WKNavigationDelegate and evaluateJavaScript

This code will change the background colour of the webpage you are displaying to red.

To show how this works, I created a simple sample app with a series of buttons with colour choices on:

Clicking on any of the buttons takes you to a webView which displays www.google.co.uk but the background colour of the webpage changes depending on the button chosen. So if you click on green you're taken to this page:

To do this, in the ViewController I added an IBAction which performs the segue when a button is tapped. The button text is then passed through to the WebViewController:

In the WebViewController there is a function getHexColour which determines the hex code colour based on the colour set in the segue.

Then in webViewDidFinish I created the css and JavaScript and applied that to the webView using the evaluateJavascript function:

Here's a link to the sample project code: https://github.com/Ceri-anne/WebViewCss

 

Top comments (3)

Collapse
 
danielsalare profile image
Daniel Salazar

Great!! Thanks

Collapse
 
ben profile image
Ben Halpern

Thanks for this, just what I needed.

Collapse
 
farhanaxmustafa profile image
Farhana

This really helped me learn what evaluateJavaScript() does! Thank you