.css in your Xcode Project 🎍
Yeah you read that right! So recently I had encountered this requirement where I was supposed to load HTML strings in a Web view in my iOS app with clickable links, and some custom font. So here’s how I 👩💻 it
Creating a .css file
⏩ Open Text Edit (Ensure you have ‘Make Plain Text’ selected under Format, or you might keep wondering how to save with .css extension)
⏩ Scribble down your css code that you would want to apply on your web view’s HTML string (In my case I wanted 2 types of fonts, some custom properties on links and an image instead of a bullet item, so below is what my css file looks like)
@font-face{font-family: 'Gotham-Book';src: local('Gotham-Book'),url('Gotham-Book.otf') format('opentype');}@font-face{font-family: 'Gotham-Medium';src: local('Gotham-Medium'),url('Gotham-Medium.otf') format('opentype');}a {color: #16A4FA;text-decoration: none;}li {margin: 0 0 0 -30px;padding: 10px 0 10px 40px;list-style: none;background-image: url('myImage.png');background-repeat: no-repeat;background-position: left top 8px;background-size: 30px;}
Here, Note that if you want some images to be loaded in your web view you will have to add them as a resource file in your project (It won’t load from your Assets.xcassets)
⏩ Save with .css extension🎍
Add .css in xcworkspace
It’s as easy as adding some resource file
⏩ Add your file by dragging it to your desired location, and copy items if needed
⏩ Ensure your file is present in the Build Phases > Copy Bundle Resources list
Loading HTML string in your web view
I just made an extension (as usual) for WKWebview to load HTML strings
And calling would be
/// webView is a WKWebView.webView.loadHTML(fromString: "yourHTMLStringGoesHere")
And I went from Left to Right
Working on WKWebView was interesting ☘ and when I saw my web view with custom fonts and this image in place of those regular bullet symbols 🙄, I re-watched my screen for like 3 to 4 times [we all do it sometimes, don’t we? 😌]