I am updating my iOS app to replace UIWebView
with WKWebView
. However I don't understand how to achieve the same behavior with WKWebView
. With UIWebView
I used scalesPageToFit
to ensure the web pag was displayed with the same size as the screen size (so as to appear full screen without scrolling).
I found that solution on the web however it does not work :
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation { NSString *javascript = @"var meta = document.createElement('meta');meta.setAttribute('name', 'viewport');meta.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no');document.getElementsByTagName('head')[0].appendChild(meta);"; [webView evaluateJavaScript:javascript completionHandler:nil]; }
WKWebView - This view allows developers to embed web content in your app. You can think of WKWebView as a stripped-down version of Safari. It is responsible to load a URL request and display the web content. WKWebView has the benefit of the Nitro JavaScript engine and offers more features.
Open “Main. storyboard” and on your ViewController's view drag “WebKit View” i.e. WKWebView. Select a WKWebView and place on your view of a view controller.
Difference Between UIWebview and WKWebViewUIWebview is a part of UIKit, so it is available to your apps as standard. You don't need to import anything, it will we there by default. But WKWebView is run in a separate process to your app,. You need to import Webkit to use WKWebView in your app.
A WKWebView object is a platform-native view that you use to incorporate web content seamlessly into your app's UI. A web view supports a full web-browsing experience, and presents HTML, CSS, and JavaScript content alongside your app's native views.
you can also try the WKUserScript.
here's my working config:
NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);"; WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES]; WKUserContentController *wkUController = [[WKUserContentController alloc] init]; [wkUController addUserScript:wkUScript]; WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init]; wkWebConfig.userContentController = wkUController; wkWebV = [[WKWebView alloc] initWithFrame:self.view.frame configuration:wkWebConfig];
you can add additional configuration to your WKWebViewConfiguration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With