Search code examples
iosswiftnsattributedstring

Attributed string not working on Label


I am setting attribute on label my code is written below, the only problem is my font and color is not getting rendered on label .

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)")
            }
        }

    }

can anyone help?


Solution

  • NSAttributedString(data:options:documentsAttributes) doesn't support NSFontAttributeName and NSForegroundColorAttributeName in its options. They will be ignored.

    So, you have to use a NSMutableAttributedString, and add your own effects afterwards:

    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
    

    Note: I don't know if it compiles, but you should get the idea.

    I posted the answer to have a "Swift way" of understanding the issue, but it's clearly a duplicate and will happily delete the answer if the question if flagged as such.