webView

  • webView--圖片自適應(yīng)屏幕
  1. HTML修改
  2. 代碼修改
-(void)viewDidLoad {
    [super viewDidLoad];
//  設(shè)置webView
    UIWebView *webView=[[UIWebView alloc]initWithFrame:self.view.bounds];
//  1、本地html資源測試
//  NSString *path=[[NSBundle mainBundle]pathForResource:@"test" ofType:@"html"];
//  [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:path]]];

//  2、URL網(wǎng)址資源測試
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://gb.wallpapersking.com/top/class108/15041/14eec4d8b4bf1fe0.htm"]]];

    [self.view addSubview:webView];
    webView.delegate=self;
}
-(void)webViewDidFinishLoad:(UIWebView *)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();"];
}

在請求內(nèi)部設(shè)置

// 網(wǎng)絡(luò)請求加載的數(shù)據(jù),進(jìn)行字典轉(zhuǎn)模型
NSDictionary *dict = [result objectForKey:@"data"];
HQNewsDetailModel *model = [HQNewsDetailModel mj_objectWithKeyValues:dict];

/**
 * model.details就是后臺返回的HTMLString
 * " $img[p].style.width = '100%%';\n"--->就是設(shè)置圖片的寬度的
 * 100%代表正好為屏幕的寬度
 */
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>",model.details];

// webView直接加載HTMLString
[self.webView loadHTMLString:htmlString baseURL:nil];
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容