Recently in the app, you need to open a local HTML file, after iOS 8, Apple introduced a new framework Wekkit, with Wkwebview instead of UIWebView, because Wkwebview "accounted for the low memory, speed," the advantages of So just use Wkwebview to load the local HTML file.
First introduce the header file #import <webkit/webkit.h>, initialize the WebView:
Initialization
Wkwebview *webview = [[Wkwebview alloc] init];
Webview.frame = Self.view.bounds;
[Self.view Addsubview:webview];
Next, load the local text.html with WebView:
NSString *path = [[NSBundle mainbundle] pathforresource:@ "text" oftype:@ "html"];
Nsurl *bundleurl = [Nsurl fileurlwithpath:[[nsbundle mainbundle] Bundlepath]];
Nserror *error = nil;
NSString *html = [[NSString alloc] Initwithcontentsoffile:path encoding:nsutf8stringencoding error:&error];
if (Error = = nil) {
[WebView loadhtmlstring:html Baseurl:bundleurl];
}
Finally command +r, found the problem, left and right both sides have a large gap. This can only be manually scaled by the customer, of course, the user experience is not good.
Original effect Diagram
In UIWebView, this scalespagetofit can be self-adaptive screen, but there is no such attribute in Wkwebview, in order to solve this problem, there are two methods: 1, directly in the HTML file source code to change. 2. Modify the size of the string in HTML by JS. The second method I used,
You first need to instantiate the wkwebviewconfiguration when instantiating the Wkusercontentcontroller class and assign it to the properties of Confiuration: Usercontentcontroller.
Wkwebviewconfiguration *wkwebconfig = [[Wkwebviewconfiguration alloc] init];
Adaptive screen Width js
NSString *jsstring = @ "var meta = document.createelement (' meta '); Meta.setattribute (' name ', ' viewport '); Meta.setattribute (' content ', ' width=device-width '); document.getElementsByTagName (' head ') [0].appendchild (meta); ";
Wkuserscript *wkuserscript = [[Wkuserscript alloc] initwithsource:jsstring injectiontime: Wkuserscriptinjectiontimeatdocumentend Formainframeonly:yes];
Add Adaptive screen Width js call method
[Wkucontroller Adduserscript:wkuserscript];
Wkwebview *webview = [[Wkwebview alloc] InitWithFrame:self.view.bounds configuration:wkwebconfig];
[Self.view Addsubview:webview];
Then load the text.html file as described above, Run
Modified effect Diagram
OK, although the title is a bit ugly, but the desired effect is out.