一:第一种方法直接加载
1. 初始话一个UIWebView:
self.webView = [[[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 0)] autorelease];
(这里需要注意的一点是,frame的高度一定要设置为0,方便后面动态设置高度);
2. 设置UIWebView的delegate:
self.webView=self(这个就不多说了)
3. 实现UIWebView 的代理方法webViewDidFinishLoad:
- (void)webViewDidFinishLoad:(UIWebView *)webView{
CGRect rect= webView.frame;
rect.size.height=webView.scrollView.contentSize.height;(此方法是将webView.scrollView的contentSize的高度赋给webView的高度,所以之前在初始化webView的时候将webView的默认高度设置为0意义就在于此,这样contentSize.height就是内容的高度了)
NSLog(@"-----%f",webView.scrollView.contentSize.height);
webView.frame=rect;
}
3. 缺点
里面的图片不会自适应
二:第二种方法:转义之后加载,图片能自适应屏幕
NSInteger width = self.webView.frame.size.width * 0.95;
方法一 :
NSString *string = [NSString stringWithFormat:@"<head><style>img{max-width:%ldpx !important;}ul {margin:0; padding:0; text-align:left;}</style><head>", (long)width];
方法二 :
NSString *string = [NSString stringWithFormat:@"<head><style>body, div, span, a, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, p, th, td, pre, form, fieldset, legend, input, button, textarea, select {margin:0;padding:5;}img{max-width:%ldpx !important;}li {list-style:none;}</style><head>", (long)width];
NSString *newHtml = [self HTML:model.body];
NSString *str = [NSString stringWithFormat:@"%@%@", string, newHtml];
[self.webView loadHTMLString:str baseURL:nil];
注 : li {list-style:none;} //去掉li的小黑点
img{max-width:%ldpx !important;} // 图片宽度自定义
ul {margin:0; padding:0; text-align:left;} // 左对齐
select {margin:0;padding:5;}//文字距离边缘的数
#pragma mark -- 转义html中的标签
- (NSString *)HTML:(NSString *)html{
NSScanner *theScaner = [NSScanner scannerWithString:html];
NSDictionary *dict = @{@"&":@"&", @"<":@"<", @">":@">", @" ":@"", @""":@"\"", @"width":@"wid"};
while ([theScaner isAtEnd] == NO) {
for (int i = 0; i <[dict allKeys].count; i ++) {
[theScaner scanUpToString:[dict allKeys][i] intoString:NULL];
html = [html stringByReplacingOccurrencesOfString:[dict allKeys][i] withString:[dict allValues][i]];
}
}
return html;
}