2016-05-31 8 views
0

Ich bin Attribut auf Etikett setzen mein Code ist unten geschrieben, das einzige Problem ist meine Schrift und Farbe wird nicht auf Etikett gerendert.Zugeschnittene Zeichenfolge funktioniert nicht auf Etikett

func setDataWithContent(content: EmbeddedContent) { 

     if let htmlString = content.text { 
      do { 
       let encodedData = htmlString.dataUsingEncoding(NSUTF8StringEncoding)! 
       let attributedOptions : [String: AnyObject] = [ 
        NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, 
        NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding, 
        NSFontAttributeName: UIFont(name: "SourceSansPro-Regular", size:16)!, 
        NSForegroundColorAttributeName: UIColor.redColor() 
       ] 
       let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil) 
       htmlTextLabel.attributedText = attributedString 

      } catch { 
       fatalError("Error: \(error)") 
      } 
     } 

    } 

kann jemand helfen?

+1

Das ist normal. Sehen Sie sich das Dokument 'NSAttributedString (data: options: documentsAttributes:)' an. 'NSFontAttributeName' und' NSForegroundColorAttributeName' werden ignoriert. Bei ihnen danach zum 'attributedString' (kann dann einen' NSMutableAttributedString' verwenden, um seine Attribute modifizieren zu können.). – Larme

+0

http://stackoverflow.com/questions/27728466/use-multiple-font-colors-in-a-single-label-swift/27728516#27728516 –

Antwort

1

NSAttributedString(data:options:documentsAttributes) unterstützt und NSForegroundColorAttributeName in seinen Optionen nicht. Sie werden ignoriert.

Also, müssen Sie eine NSMutableAttributedString verwenden und eigene Effekte hinzufügen, danach:

let encodedData = htmlString.dataUsingEncoding(NSUTF8StringEncoding)! 

let attributedOptions : [String: AnyObject] = [ 
    NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, 
    NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding 
] 
let attributedString = try NSMutableAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil) 
let addedEffects:[String:AnyObject] = [          
    NSFontAttributeName: UIFont(name: "SourceSansPro-Regular", size:16)!, 
    NSForegroundColorAttributeName: UIColor.redColor() 
] 
attributedString.addAttributes(addedEffects, range:NSRange(location:0,length:attributedString.length) 
htmlTextLabel.attributedText = attributedString 

Hinweis: Ich weiß nicht, ob es kompiliert, aber man sollte die Idee.

Ich habe die Antwort veröffentlicht, um einen "schnellen Weg" zu haben, das Problem zu verstehen, aber es ist eindeutig ein Duplikat und wird glücklich die Antwort löschen, wenn die Frage als so gekennzeichnet wird.

+0

Sie können diese Antwort nicht löschen, nachdem sie akzeptiert wurde. – JAL

+0

Ups, hatte das nicht erwartet. Dachte auch, dass das OP seine Frage als Duplikat markieren würde. – Larme

Verwandte Themen