最近在app中,需要打開一個(gè)本地的html文件,在iOS 8以后蘋果推出了一個(gè)新的框架Webkit,用WKWebView代替了UIWebView,鑒于WKWebView“占內(nèi)存少,速度快”的優(yōu)點(diǎn),所以就用WKWebView去加載本地的html文件。
首先引入頭文件#import <WebKit/WebKit.h>,初始化webView:
// 初始化
WKWebView *webView = [[WKWebView alloc] init];
webView.frame = self.view.bounds;
[self.view addSubview:webView];
接下來,利用webView加載本地text.html:
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];
}
最后command +r一下,發(fā)現(xiàn)問題了,左右兩邊都有大片的空白。這樣只能客戶自己手動(dòng)縮放,當(dāng)然用戶體驗(yàn)不好。

在UIWebView中,這個(gè)scalesPageToFit是可以自適應(yīng)屏幕的,但是WKWebView中沒有這個(gè)屬性,為了解決這個(gè)問題,有兩個(gè)方法:1、直接在html文件的源碼中改。2、通過js修改html中字符串的大小。我采用的第二種方法,
首先需要在實(shí)例化WKWebViewConfiguration時(shí) 實(shí)例 WKUserContentController類并將其賦值給confiuration的屬性:userContentController。
WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
// 自適應(yīng)屏幕寬度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];
// 添加自適應(yīng)屏幕寬度js調(diào)用的方法
[wkUController addUserScript:wkUserScript];
WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:wkWebConfig];
[self.view addSubview:webView];
然后再按上面的方法加載text.html文件,Run

OK了,雖然標(biāo)題有點(diǎn)丑,但想要的效果還是出來了。