Updated 26 October 2021
We can use CSS in our WKWebView to handle the layouts according to our usage.
Please find an example for using the CSS in WKWebView in swift :-
1 2 3 |
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
1 |
@IBOutlet var descriptionWebView: WKWebView! |
Call the delegate in class
1 |
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 func for applying the CSS in webview :
1 2 |
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { } |
The whole code given below that will help you to connect all the functionality :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
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.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.