属性字符串不适用于标签

Attributed string not working 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)")
            }
        }

    }

有人能帮忙吗?

NSAttributedString(data:options:documentsAttributes) 的选项不支持 NSFontAttributeNameNSForegroundColorAttributeName。 他们将被忽略。

因此,您必须使用 NSMutableAttributedString,然后添加您自己的效果:

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

注意:我不知道它是否编译,但你应该明白了。

我发布答案是为了 "Swift way" 理解这个问题,但它显然是重复的,如果问题被标记为这样,我会很乐意删除答案。