增加HTML解析字符串的字体大小 - 目标C.

时间:2017-02-27 11:57:52

标签: ios objective-c nsattributedstring

dummyString是我的HTML内容,以字符串形式存储。然后我正在使用,

 dummyString = [NSString stringWithFormat:@"<span style=\"font-family: HelveticaNeue-Thin; font-size: 18\">%@</span>", dummyString];

设置属性(18是我的默认字体大小)。

然后我使用以下代码行来解析要在UIScrollView中显示的HTML内容。

NSMutableAttributedString *dummy = [[NSMutableAttributedString alloc]
                                 initWithData: [dummyString dataUsingEncoding:NSUnicodeStringEncoding]
                                 options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
                                 documentAttributes: nil
                                 error: nil
                                 ];

如果我将字体大小从默认值(18)更改为其他大小(例如36),则文本大小不会增加,而是字母间距会增加。添加屏幕截图:

font-size == 18

font-size == 36

我无法理解我做错了什么!

2 个答案:

答案 0 :(得分:0)

我已经迅速写了这篇文章。我删除了旧字体,并在整个范围内添加了自己的字体。

let   dummyString = NSString(format:"<span style=\"font-family: HelveticaNeue-Thin; font-size: 9\">hi this string</span>")

    do{
        let attributedString = try NSMutableAttributedString.init(data:dummyString.data(using: String.Encoding.unicode.rawValue)!, options:[NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType], documentAttributes:nil)

        attributedString.beginEditing()
        attributedString.enumerateAttribute(NSFontAttributeName, in:NSMakeRange(0,attributedString.length), options: NSAttributedString.EnumerationOptions(rawValue: 0), using: { (vaue, range, stop) in
            attributedString .removeAttribute(NSFontAttributeName, range:range)
            // you can use any font
            let newFont = UIFont.boldSystemFont(ofSize:25)
            attributedString.addAttribute(NSFontAttributeName, value: newFont, range:range)
        })
        attributedString.endEditing()
    textView.attributedText = attributedString
    }catch{
    }
}

希望这有助于:)

答案 1 :(得分:0)

@implementation UILabel (HTML)

- (void)jaq_setHTMLFromString:(NSString *)string {

string = [string stringByAppendingString:[NSString stringWithFormat:@"  <style>body{font-family: '%@'; font-size:%fpx;}</style>",
                                          self.font.fontName,
                                          self.font.pointSize]];
self.attributedText = [[NSAttributedString alloc] initWithData:[string dataUsingEncoding:NSUnicodeStringEncoding]
                                                       options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                                                 NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
                                            documentAttributes:nil
                                                         error:nil];
}