iOSUIwebview自適應加載圖片

當我們使用webview加載html時,如果html的內容包含圖片,有時會顯示特別大,那麼就需要我們進行自適應,在webview加載結束的代理方法裏面添加以下代碼則可以解決:
NSString *js=@“var script = document.createElement(‘script’);”
“script.type = ‘text/javascript’;”
"script.text = “function ResizeImages() { "
“var myimg,oldwidth;”
“var maxwidth = %f;”
“for(i=0;i <document.images.length;i++){”
“myimg = document.images[i];”
“if(myimg.width > maxwidth){”
“oldwidth = myimg.width;”
“myimg.width = %f;”
“}”
“}”
“}”;”
“document.getElementsByTagName(‘head’)[0].appendChild(script);”;
js=[NSString stringWithFormat:js,[UIScreen mainScreen].bounds.size.width,[UIScreen mainScreen].bounds.size.width-15];
[webView stringByEvaluatingJavaScriptFromString:js];
[webView stringByEvaluatingJavaScriptFromString:@“ResizeImages();”];

再使用以下方法可以獲取webview的最終內容高度
//獲取到webview的高度
CGFloat height = [[self.webView stringByEvaluatingJavaScriptFromString:@“document.body.offsetHeight”] floatValue];

獲取html內容的標題
NSString *htmlTitle = @“document.title”;
NSString *titleHtmlInfo = [webView stringByEvaluatingJavaScriptFromString:htmlTitle];
注意:都是在webview加載結束的代理方法下使用纔有效

  • (void)webViewDidFinishLoad:(UIWebView *)webView
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章