2017-06-12 6 views
0

J'ai un contenu HTML que je veux rendre dans mon UILabel natif, mais en plus de cela, je dois ajouter une police personnalisée à cet UILabel. J'utilise NSAttributedString pour le faire et en utilisant le code suivant pour rendre le contenu HTML dans mon UILabel.Ajout d'attributs de police au rendu HTML UILabel swift

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() 

Le problème ici est que lorsque j'applique des attributs de police sur la chaîne HTML rendue. Ensuite, tout le formatage HTML comme gras est perdu.

Ainsi est-il possible que je peux appliquer une police sélectionnée sur HTML chaîne attribué rendu

+0

https://stackoverflow.com/a/44435915/5362916 vérifier celui- –

+0

Utilisez ce lien: https://stackoverflow.com/questions/28496093/making-text-bold-using-attributed-string -in-swift – ashwini

+0

@UmaMadhavi votre lien a fonctionné pour moi. merci – Madu

Répondre

0

Remplacer la police selon vos besoins.

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

Pour moi, il remplacer tout le formatage dans le contenu HTML d'origine – Madu

+0

Depuis gras/italique et la taille sont à l'intérieur du 'UIFont', il perd ses spécificités. Itère pour le 'NSFontAttributeName' et modifie chaque valeur, ou édite le code HTML. – Larme