一:第一種方法直接加載
1. 初始話一個(gè)UIWebView:
self.webView = [[[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 0)] autorelease];
(這里需要注意的一點(diǎn)是,frame的高度一定要設(shè)置為0俄删,方便后面動(dòng)態(tài)設(shè)置高度)疗锐;
2. 設(shè)置UIWebView的delegate:
self.webView=self(這個(gè)就不多說(shuō)了)
3. 實(shí)現(xiàn)UIWebView 的代理方法webViewDidFinishLoad:
- (void)webViewDidFinishLoad:(UIWebView *)webView{
CGRect rect= webView.frame;
rect.size.height=webView.scrollView.contentSize.height;(此方法是將webView.scrollView的contentSize的高度賦給webView的高度愉豺,所以之前在初始化webView的時(shí)候?qū)ebView的默認(rèn)高度設(shè)置為0意義就在于此允乐,這樣contentSize.height就是內(nèi)容的高度了)
NSLog(@"-----%f",webView.scrollView.contentSize.height);
webView.frame=rect;
}
3. 缺點(diǎn)
里面的圖片不會(huì)自適應(yīng)
二:第二種方法:轉(zhuǎn)義之后加載矮嫉,圖片能自適應(yīng)屏幕
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的小黑點(diǎn)
img{max-width:%ldpx !important;} // 圖片寬度自定義
ul {margin:0; padding:0; text-align:left;} // 左對(duì)齊
select {margin:0;padding:5;}//文字距離邊緣的數(shù)
#pragma mark -- 轉(zhuǎn)義html中的標(biāo)簽
- (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;
}