ios - 属性字符串不适用于标签

标签 ios swift nsattributedstring

<分区>

我在标签上设置属性我的代码写在下面, 唯一的问题是我的字体和颜色没有在标签上呈现。

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

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

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

关于ios - 属性字符串不适用于标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37546681/

上一篇:ios - 如何在不丢失选项卡的情况下在选项卡式应用程序上加载另一个 View Controller

下一篇:ios - 网页加载时间代码片段仅适用于 https 网站

相关文章:

ios - Core Audio 从 AudioQueue(或 AudioUnits)获取数据到内存中

ios - 使用 scrollViewDidScroll 移动 ChildViewController 的 subview

html - 后台线程中来自 HTML 的 NSAttributedString

ios - 分别翻转字符串中的字符

objective-c - NSPredicate 连接属性

ios - 如何在不同的 View Controller 中分离模块

swift - 在实现协议(protocol)的结构上调用方法

swift - 将自定义 UIView 添加到 View 后,UICollectionView 不滚动

ios - 如何修改 NSTextAttachement 在 uilabel 中的位置?

iphone - 导航栏没有立即改变背景 - IOS