美文网首页
iOS中用富文本展示Html内容的问题【不能加粗,图片展示等】

iOS中用富文本展示Html内容的问题【不能加粗,图片展示等】

作者: 这位网友 | 来源:发表于2021-05-27 11:12 被阅读0次
    图片展示需要添加代码:
    htmlString =  [NSString stringWithFormat:@"<head><style>img{width:%f !important;height:auto}</style></head>%@", imageWidth, htmlString];`
    
    有加粗字体需要添加代码:( 参考NSAttributedString转换:粗体,<b>-标签,不起作用
    htmlString = [NSString stringWithFormat:@"<style>body{font-family: '%@'; font-size:%fpx;}</style>%@", font.fontName, font.pointSize, htmlString];
    
    示例:
    + (NSMutableAttributedString *)getAttributedStringByHTMLString:(NSString *)htmlString
                                                        imageWidth:(CGFloat)imageWidth
                                                      textAligment:(NSTextAlignment)textAligment
                                                     lineBreakMode:(NSLineBreakMode)lineBreakMode
                                                       lineSpacing:(CGFloat)lineSpacing
                                                              font:(UIFont *)font
                                                             color:(nullable UIColor *)color {
        if (imageWidth > 0 && [htmlString containsString:@"<img"]) {
            htmlString = [NSString stringWithFormat:@"<head><style>img{width:%f !important;height:auto}</style></head>%@", imageWidth, htmlString];
        }
        
        if (font) { //因为设置了font,不能再使用NSFontAttributeName属性来设置,加粗字体等样式会被覆盖掉
            htmlString = [NSString stringWithFormat:@"<style>body{font-family: '%@'; font-size:%fpx;}</style>%@", font.fontName, font.pointSize, htmlString];
        }
        
        NSDictionary *options = @{ NSDocumentTypeDocumentAttribute      : NSHTMLTextDocumentType,
                                   NSCharacterEncodingDocumentAttribute : @(NSUTF8StringEncoding) };
        NSData *data = [htmlString dataUsingEncoding:NSUTF8StringEncoding];
        
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithData:data options:options documentAttributes:nil error:nil];
        NSMutableParagraphStyle *paragraphStyle     = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.lineBreakMode                = lineBreakMode;
        [paragraphStyle setLineSpacing:lineSpacing];
        [paragraphStyle setAlignment:textAligment];
        
        NSRange range = NSMakeRange(0, [attributedString length]);
        [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range];
        
        if (color) {
            [attributedString addAttribute:NSForegroundColorAttributeName value:color range:range];
        }
        
        return attributedString;
    }
    

    相关文章

      网友评论

          本文标题:iOS中用富文本展示Html内容的问题【不能加粗,图片展示等】

          本文链接:https://www.haomeiwen.com/subject/vfvrsltx.html