ios 使用富文本加载HTML

富文本设置

  1. \n替换
  2. 图片宽度设置
  3. 行间距设置
-(NSMutableAttributedString *)setAttributedString:(NSString *)str
{
//如果有换行,把\n替换成<br/>
//如果有需要把换行加上
 str = [str stringByReplacingOccurrencesOfString:@"\n" withString:@"<br/>"];
//设置HTML图片的宽度
 str = [NSString stringWithFormat:@"<head><style>img{width:%f !important;height:auto}</style></head>%@",[UIScreen mainScreen].bounds.size.width,str];
 NSMutableAttributedString *htmlString =[[NSMutableAttributedString alloc] initWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute:[NSNumber numberWithInt:NSUTF8StringEncoding]} documentAttributes:NULL error:nil];
//设置富文本字的大小
 [htmlString addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} range:NSMakeRange(0, htmlString.length)];
//设置行间距
 NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle1 setLineSpacing:5];
 [htmlString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [htmlString length])];

    return htmlString;
}

获取富文本的高度

//计算html字符串高度
-(CGFloat )getHTMLHeightByStr:(NSString *)str
{
  str = [str stringByReplacingOccurrencesOfString:@"\n" withString:@"<br/>"];
  str = [NSString stringWithFormat:@"<head><style>img{width:%f !important;height:auto}</style></head>%@",[UIScreen mainScreen].bounds.size.width,str];

    NSMutableAttributedString *htmlString =[[NSMutableAttributedString alloc] initWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute:[NSNumber numberWithInt:NSUTF8StringEncoding]} documentAttributes:NULL error:nil];
    [htmlString addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} range:NSMakeRange(0, htmlString.length)];
    //设置行间距
    NSMutableParagraphStyle *paragraphStyle1 = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle1 setLineSpacing:5];
    [htmlString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle1 range:NSMakeRange(0, [htmlString length])];
    
    CGSize contextSize = [htmlString boundingRectWithSize:(CGSize){[UIScreen mainScreen].bounds.size.width), CGFLOAT_MAX} options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil].size;
    return contextSize.height ;
    
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 14,679评论 1 92
  • 冬夜踏园寻雪踪 曲径幽幽月朦胧 忽闻扑鼻清香至 原是腊梅唤春风 20170131
    行者无疆之阅读 2,695评论 0 0
  • 你说芰荷抖攒,熠然风华;后来泪脸青房,滚珠入画。 你说子夜悠长,暗香扰窗;后来白水月华,及地成霜。 你说青伞桃花,...
    眉眼娇怯阅读 4,104评论 30 25
  • 每日金句 如果你有梦想就请你捍卫它 -【早起打卡】20180804 05:09 -践行人员 余莎 -【践行天数】5...
    Cherishyu阅读 1,196评论 0 0
  • 嘟嘟说,妈妈,我想自己带饭菜去学校,学校里午餐提供的那些饭菜都不好吃! 我说,那我问一下班主任!老师回复,不可以。...
    妖精欣儿阅读 1,423评论 0 0