在實(shí)際開發(fā)中, 我們經(jīng)常會(huì)用到 UIWebView, 但是有時(shí)候 富文本里面有圖片時(shí)就會(huì)有問(wèn)題,(圖片的寬度往往會(huì)超過(guò)屏幕寬),這個(gè)時(shí)候就需要我們手動(dòng)添加CSS樣式, 拼接HTML格式.
| OC 版
- (void)dealNewsData:(NSDictionary *)dataDic{
// 取出所有的內(nèi)容
NSDictionary * allData = dataDic[@"BJ5NRE5T00031H2L"];
// 取出body中的內(nèi)容
NSString * bodyData = allData[@"body"];
// 取出標(biāo)題
NSString * title = allData[@"title"];
// 取出發(fā)布時(shí)間
NSString * ptime = allData[@"ptime"];
// 取出來(lái)源
NSString * source = allData[@"source"];
// 取出圖片資源
NSArray * imgArr = allData[@"img"];
// 遍歷
for (int i = 0; i < imgArr.count; i ++) {
NSDictionary * imgItem = imgArr[i];
// 取出占位符
NSString * ref = imgItem[@"ref"];
// 取出圖片標(biāo)題
NSString * imgTitle = imgItem[@"alt"];
// 取出src
NSString * src = imgItem[@"src"];
// NSString * imgHTML = @"<div class = \"all-img\"> <img src = \"\(src)\"></div> ";
NSString * imgHtml = [NSString stringWithFormat:@"<div class=\"all-img\"><img src=%@><div>%@</div></div>",src,imgTitle];
bodyData = [bodyData stringByReplacingOccurrencesOfString:ref withString:imgHtml];
}
// 創(chuàng)建標(biāo)題的HTML標(biāo)簽
NSString * titleHTML = [NSString stringWithFormat:@"<div id = \"mainTitle\">%@</div>",title];
// 創(chuàng)建子標(biāo)簽的HTML標(biāo)簽
NSString * subTitleHtml = [NSString stringWithFormat:@"<div id = \"subTitle\"><span class = \"time\">%@</span><span>%@</span></div>",ptime,source];
// 加載css的url 路徑
NSURL * css = [[NSBundle mainBundle] URLForResource:@"newsDetail" withExtension:@"css"];
// 創(chuàng)建html 標(biāo)簽
NSString * cssHtml = [NSString stringWithFormat:@"<link href=%@ rel=\"stylesheet\">",css];
// 加載js的URL 路徑
NSURL * js = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"js"];
// 創(chuàng)建html標(biāo)簽
NSString * jsHtml = [NSString stringWithFormat:@"<script src=%@></script>",js];
NSString * html = [NSString stringWithFormat:@"<html><head>%@</head><body>%@%@%@%@</body></html>",cssHtml,titleHTML,subTitleHtml,bodyData,jsHtml];
//NSLog(@"html -%@",html);
[self.webView loadHTMLString:html baseURL:nil];
}
| Swift版
let ImageCss = NSBundle.mainBundle().URLForResource("newsDetail", withExtension: "css")
let cssHtml = "<link href=\(ImageCss!) rel=\"stylesheet\">"
let html = "<html><head>\(cssHtml)</head><body>\(dataInfo["content"] as! String)</body></html>"
self.web.loadHTMLString(html, baseURL: nil)
注意: id 用 # class 用 .
| css 樣式表
body{
background-color:red;
}
img{
width:100%;
}
#mainTitle{
text-align:center;
font-size:20px;
margin-top:25px;
margin-bottom:10px;
}
#subTitle{
color:gray;
text-align:left;
}
.time{
margin-right:10px;
margin-bottom:10px;
}
.all-img{
color;gray;
text-align:center;
margin:8px 0;
}
通過(guò)上面的方法,就能解決圖片太寬問(wèn)題