How to use CSS in WKWebView?

Sachin Khard
1 min readSep 17, 2019

--

We can use CSS in our WKWebView to handle the layouts according to our usage.

Below is the example of CSS and Javascript :-

let css = “img {max-width: 100%; width: 100%; height: 75%; vertical-align: middle;}”

let js = “var style = document.createElement(‘style’); style.innerHTML = ‘\(css)’; document.head.appendChild(style);”

The above two lines helps to set the size of the images inside the WKWebView. We can use any of the CSS according to our use.

Drag and drop a WKWebView in view controller

@IBOutlet var descriptionWebView: WKWebView!

set the delegate in class

descriptionWebView.navigationDelegate = self

There is one delegate method that helps in showing the data accurately according to the CSS applied to it. Use the below delegate function for applying the CSS in webview :

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

}

The whole code given below that will help you to connect all the functionality :

class WebviewUsingCSS: UIViewController, WKNavigationDelegate {

@IBOutlet var cssWebView: WKWebView!

var descriptionData:String!

override func loadView() {

cssWebView = WKWebView()

cssWebView.navigationDelegate = self

view = cssWebView

}

override func viewDidLoad() {

super.viewDidLoad()

self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false

self.title = GlobalData.sharedInstance.language(key: “description”)

// cssWebView. scalesPageToFit = true

self.cssWebView.loadHTMLString(descriptionData, baseURL: nil)

}

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

let css = “img {max-width: 100%; width: 100%; height: 75%; vertical-align: middle;}”

let js = “var style = document.createElement(‘style’); style.innerHTML = ‘\(css)’; document.head.appendChild(style);”

cssWebView.evaluateJavaScript(js, completionHandler: nil)

}

}

Hope the above blog will help you in understanding the use of CSS in WKWebView in swift.

--

--

Sachin Khard
Sachin Khard

Written by Sachin Khard

Independent iOS developer, author, trainer

No responses yet