直接贴代码了;已经懒到极致了!
需求: 解决服务器传过来的js代码,并正确的按想要的排版方式显示在页面上(即适配移动端各个屏幕)
解决方案: 加载前提前拦截修改适配样式 (当然也可以前端做适配各个平台, 不过移动端做了处理就不用理会前端是否适配的问题)
处理的问题有: 适配文字大小; 适配图片大小; 适配视频大小;
- (void)parseHTMLWithHtml:(NSString *)htmls {
self.content.alpha = 0;
self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(_imagesView.frame) , kWIDTH_SCREEN -30, kHEIGHT_SCREEN/2 )];
[self.scroll addSubview:self.webView];
self.webView.scrollView.scrollEnabled = NO;
self.webView.delegate = self;
self.webView.backgroundColor = [UIColor whiteColor];
self.scroll.contentSize = CGSizeMake(kWIDTH_SCREEN -30 , CGRectGetMaxY(self.webView.frame)+64+20);
[SVProgressHUD showWithStatus:@"努力加载..."];
htmls = [htmls stringByReplacingOccurrencesOfString:@"<br/>" withString:@""];
[self.webView loadHTMLString:htmls baseURL:nil];
[self.webView addObserver:self forKeyPath:@"loading" options:NSKeyValueObservingOptionNew context:nil];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
[webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '75%'"];
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-30 ,[UIScreen mainScreen].bounds.size.width-45];
[webView stringByEvaluatingJavaScriptFromString:js];
[webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
NSString *js2 =@"var script = document.createElement('script');"
"script.type = 'text/javascript';"
"script.text = \"function ResizeVideo() { "
"var number = (document.getElementsByTagName('iframe')[0].height / document.getElementsByTagName('iframe')[0].width);"
"document.getElementsByTagName('iframe')[0].width= %f;"
"document.getElementsByTagName('iframe')[0].height= document.getElementsByTagName('iframe')[0].width * number ;"
"}\";"
"document.getElementsByTagName('head')[0].appendChild(script);";
js2 = [NSString stringWithFormat:js2,[UIScreen mainScreen].bounds.size.width-30 ];
[webView stringByEvaluatingJavaScriptFromString:js2];
[webView stringByEvaluatingJavaScriptFromString:@"ResizeVideo();"];
CGFloat webViewHeight=[webView.scrollView contentSize].height;
CGRect newFrame = webView.frame;
newFrame.size.height = webViewHeight;
webView.frame = newFrame;
self.scroll.contentSize = CGSizeMake(kWIDTH_SCREEN - 30, CGRectGetMaxY(webView.frame) - kHEIGHT_SCREEN/3);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[SVProgressHUD dismiss];
});
}