<分区>
<分区>
我在标签上设置属性我的代码写在下面, 唯一的问题是我的字体和颜色没有在标签上呈现。
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)在其选项中不支持 NSFontAttributeName
和 NSForegroundColorAttributeName
。
它们将被忽略。
因此,您必须使用 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 - Core Audio 从 AudioQueue(或 AudioUnits)获取数据到内存中
ios - 使用 scrollViewDidScroll 移动 ChildViewController 的 subview
html - 后台线程中来自 HTML 的 NSAttributedString
objective-c - NSPredicate 连接属性
ios - 如何在不同的 View Controller 中分离模块
swift - 在实现协议(protocol)的结构上调用方法
swift - 将自定义 UIView 添加到 View 后,UICollectionView 不滚动