在实际开发中, 我们经常会用到 UIWebView, 但是有时候 富文本里面有图片时就会有问题,(图片的宽度往往会超过屏幕宽),这个时候就需要我们手动添加CSS样式, 拼接HTML格式.
| OC 版
- (void)dealNewsData:(NSDictionary *)dataDic{
// 取出所有的内容
NSDictionary * allData = dataDic[@"BJ5NRE5T00031H2L"];
// 取出body中的内容
NSString * bodyData = allData[@"body"];
// 取出标题
NSString * title = allData[@"title"];
// 取出发布时间
NSString * ptime = allData[@"ptime"];
// 取出来源
NSString * source = allData[@"source"];
// 取出图片资源
NSArray * imgArr = allData[@"img"];
// 遍历
for (int i = 0; i < imgArr.count; i ++) {
NSDictionary * imgItem = imgArr[i];
// 取出占位符
NSString * ref = imgItem[@"ref"];
// 取出图片标题
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];
}
// 创建标题的HTML标签
NSString * titleHTML = [NSString stringWithFormat:@"<div id = \"mainTitle\">%@</div>",title];
// 创建子标签的HTML标签
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"];
// 创建html 标签
NSString * cssHtml = [NSString stringWithFormat:@"<link href=%@ rel=\"stylesheet\">",css];
// 加载js的URL 路径
NSURL * js = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"js"];
// 创建html标签
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;
}
通过上面的方法,就能解决图片太宽问题
网友评论