WKWebView圖片文字自適應屏幕


前言

在開發中經常需要使用到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
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM