美文网首页汽车公司可能用到的知识点
WKWebView图片文字自适应屏幕

WKWebView图片文字自适应屏幕

作者: 季末微夏 | 来源:发表于2017-11-17 17:11 被阅读341次

前言

在开发中经常需要使用到WebView,然而加载HTML字符串后效果并不是全屏,这时候就需要做自适应屏幕大小。这里主要说一下WKWebView如何实现图片和文字自适应屏幕。

1.文字自适应屏幕

创建WKWebView的时候,直接添加js来实现自适应。

// 自适应屏幕宽度js
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;
WKWebView *contentWeb = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:wkWebConfig];

2.图片自适应屏幕

图片自适应屏幕采用添加HTML源码的方式来实现自适应,使用下面源码拼接上后台的HTML源码,然后直接加载既可。

NSString *htmlString = [NSString stringWithFormat:@"<html> \n"
                            "<head> \n"
                            "<style type=\"text/css\"> \n"
                            "body {font-size:15px;}\n"
                            "</style> \n"
                            "</head> \n"
                            "<body>"
                            "<script type='text/javascript'>"
                            "window.onload = function(){\n"
                            "var $img = document.getElementsByTagName('img');\n"
                            "for(var p in  $img){\n"
                            " $img[p].style.width = '100%%';\n"
                            "$img[p].style.height ='auto'\n"
                            "}\n"
                            "}"
                            "</script>%@"
                            "</body>"
                            "</html>", html];

相关文章

网友评论

    本文标题:WKWebView图片文字自适应屏幕

    本文链接:https://www.haomeiwen.com/subject/nibjvxtx.html