2017-06-12 7 views
0

私は自分のネイティブUILabelでレンダリングしたいいくつかのHTMLコンテンツを持っていますが、それに加えてカスタムフォントをそのUILabelに追加する必要があります。私はNSAttributedStringを使ってこれを行い、次のコードを使用してUILabelのHTMLコンテンツをレンダリングしています。HTMLにレンダリングされたUILabelスウィフトにフォント属性を追加する

func htmlAttributedString() -> NSAttributedString? { 
    guard let data = self.data(using: .utf16, allowLossyConversion: false) else { 
     return nil 
    } 
    guard let html = try? NSMutableAttributedString(
     data: data, 
     options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], 
     documentAttributes: nil) else { return nil } 


    let attributes = [ 
     NSForegroundColorAttributeName: UIColor.lightGray, 
     NSFontAttributeName : UIFont.systemFont(ofSize: 12) 
    ] 
    html.setAttributes(attributes, range: NSRange(0..<html.length)) 

    return html 
} 

var str = "Here is the <bold>string</bold> that i want to be bold. 
messageLabel.attributedText = str.htmlAttributedString() 

ここでの問題は、HTMLで表示される属性付き文字列にフォント属性を適用する場合です。太字のようなHTML書式はすべて失われます。

だから私は、HTML上のいくつかの選択されたフォントが属性付き文字列

+0

https://stackoverflow.com/a/44435915/5362916この1 –

+0

使用して、このリンクをチェックします。https://stackoverflow.com/questions/28496093/making-text-bold-using-attributed-string -in-swift – ashwini

+0

@UmaMadhaviあなたのリンクは私のために働いた。ありがとう – Madu

答えて

0

はあなたの条件に応じてフォントを置き換えますレンダリング適用することができる方法があります。

func htmlAttriButedText(str : String) -> NSAttributedString{ 
     let attrStr = try! NSMutableAttributedString(
      data: str.data(using: String.Encoding.utf8, allowLossyConversion: true)!, 
      options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], 
      documentAttributes: nil) 
     attrStr.addAttribute(NSForegroundColorAttributeName, value: lightTextColor, range: NSMakeRange(0, attrStr.length)) 
     attrStr.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFont(ofSize: 13), range: NSMakeRange(0, attrStr.length)) 
     return attrStr 
    } 
+0

私のために、オリジナルのHTMLコンテンツのすべての書式を置き換えます。 – Madu

+0

太字/斜体およびサイズは「UIFont」の中にあるので、その特定性が失われます。 'NSFontAttributeName'を繰り返し実行し、各値を変更するか、HTMLを自分で編集します。 – Larme

関連する問題