2017-01-12 54 views
1

我無法使用NSMutableAttributedString來讀取HTML字符串並增加它的字體大小。具有字體大小和HTML標記屬性的NSMutableAttributedString

輸入HTML:<b>Lorem ipsum</b> dolor sit <i>amet</i></h3>consectetuer</h3> adipiscing elit

而且NSMutableAttributedString轉換如下:

let htmlData = input.data(using: .utf8)! 

let htmlAttrs = [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:String.Encoding.utf8.rawValue] as [String : Any] 

do{ 
    let new = try NSMutableAttributedString(data: htmlData, options: htmlAttrs, documentAttributes: nil) 

    let tillEnd = NSRange(location: 0, length: new.length) 
    let attr:UIFont = UIFont.systemFont(ofSize: 25) 

    //new.addAttribute(NSFontAttributeName, value: attr, range: tillEnd) 

    textView.attributedText = new 
} 

它讀取正確的HTML標籤,並給出輸出

HTML properly encoded

但是,如果我想增加字體大小並取消註釋addAttribute,字體大小會增加但HTML不會呈現。

font size increase but html reading gone

我能得到屬性串既字體大小和HTML渲染?

+1

這是正常的行爲。斜體和粗體在UIFont中(以及在NSFontAttributeName中)。你需要迭代你的NSAttributedString的NSFontAttributeName這裏有一個好的開始:http://stackoverflow.com/a/41413014/1801544(馬特的答案,但不是像格魯吉亞一樣創建一個新字體,而是使用與之前相同的字體)。 – Larme

+0

謝謝,馬特的答案奏效。 – khanHussain

回答

0

您可以使用風格跨度標籤的屬性,包括CSS與字體大小財產。