编辑 - 这已被标记为重复,但正如我下面所述,我正在寻找一个Swift解决方案。我找到的所有东西都写在Objective C中。如何在NSAttributedString上设置字体大小
我想将HTML转换为NSAttributedString,但无法计算如何设置字体样式和大小。所有的例子都在目标C这我不擅长,我如何设置字体样式/大小系统15(作为一个例子)
private func stringFromHtml(string: String) -> NSAttributedString? {
do {
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
if let d = data {
let str = try NSAttributedString(data: d,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
return str
}
} catch {
}
return nil
}
编辑......我已经尝试了几种方法。我无法让它工作。我现在收到一条错误消息:表达式的类型在没有更多上下文的情况下是不明确的。它指向NSAttributedString 我已经试过如下:
let myAttribute = [ NSForegroundColorAttributeName: UIColor.blue ]
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
if let d = data {
let str = try NSAttributedString(data: d,
attributes: myAttribute,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
希望这有助于:https://stackoverflow.com/questions/24666515/我怎么做 - 使归属字符串使用swift – Amit
https://stackoverflow.com/questions/41412963/swift-change-font-on-an-html-string-that-has-its-自己的风格这一个。 – Larme
@Larme ...我使用您提供的链接中的扩展示例解决了它。可悲的是我仍然不明白。我相信我不得不创建一个NSMutableAttributedString,而我只是想改变一个Attributed String?谢谢! –