您的位置:首页 > 移动开发

WKWebView的使用-适应屏幕宽度

2016-12-01 10:01 344 查看
最近在app中,需要打开一个本地的html文件,在iOS 8以后苹果推出了一个新的框架Wekkit,用WKWebView代替了UIWebView,鉴于WKWebView“占内存少,速度快”的优点,所以就用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一下,发现问题了,左右两边都有大片的空白。这样只能客户自己手动缩放,当然用户体验不好。



原效果图

在UIWebView中,这个scalesPageToFit是可以自适应屏幕的,但是WKWebView中没有这个属性,为了解决这个问题,有两个方法:1、直接在html文件的源码中改。2、通过js修改html中字符串的大小。我采用的第二种方法,

首先需要在实例化WKWebViewConfiguration时 实例 WKUserContentController类并将其赋值给confiuration的属性:userContentController。

WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];

// 自适应屏幕宽度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];

// 添加自适应屏幕宽度js调用的方法

[wkUController addUserScript:wkUserScript];

WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:wkWebConfig];

[self.view addSubview:webView];

然后再按上面的方法加载text.html文件,Run



修改后的效果图

OK了,虽然标题有点丑,但想要的效果还是出来了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: