前言
在开发中经常需要使用到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];
作者:季末微夏
链接:https://www.jianshu.com/p/8934711eb337
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。