webView

作者: JackfengGG | 来源:发表于2017-05-22 17:56 被阅读7次
  • webView--图片自适应屏幕
  1. HTML修改
  2. 代码修改
-(void)viewDidLoad {
    [super viewDidLoad];
//  设置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网址资源测试
    [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();"];
}

在请求内部设置

// 网络请求加载的数据,进行字典转模型
NSDictionary *dict = [result objectForKey:@"data"];
HQNewsDetailModel *model = [HQNewsDetailModel mj_objectWithKeyValues:dict];

/**
 * model.details就是后台返回的HTMLString
 * " $img[p].style.width = '100%%';\n"--->就是设置图片的宽度的
 * 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];

相关文章

网友评论

      本文标题:webView

      本文链接:https://www.haomeiwen.com/subject/helixxtx.html