前言
在開發(fā)中經(jīng)常需要使用到WebView应媚,然而加載HTML字符串后效果并不是全屏,這時(shí)候就需要做自適應(yīng)屏幕大小。這里主要說一下WKWebView如何實(shí)現(xiàn)圖片和文字自適應(yīng)屏幕拷沸。
1.文字自適應(yīng)屏幕
創(chuàng)建WKWebView的時(shí)候色查,直接添加js來實(shí)現(xiàn)自適應(yīng)。
// 自適應(yīng)屏幕寬度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.圖片自適應(yīng)屏幕
圖片自適應(yīng)屏幕采用添加HTML源碼的方式來實(shí)現(xiàn)自適應(yīng)撞芍,使用下面源碼拼接上后臺(tái)的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];