数据到带有字体属性 Swift 的属性字符串

问题描述

我有一个 RTF 文件,通过它我能够将内容作为数据获取(我希望它在数据中以便在代码的其他地方使用它)。但是,我想在分配给标签之前将样式添加到类似字体的属性字符串中。我对如何在下面的代码中应用这些属性感到震惊。请建议我如何实现相同的目标。这是我的代码

let rtfData = getRTFData()
guard let data = rtfData else {
        return
    }
if let attributedString = try? NSAttributedString(data: data,options: [.documentType: NSAttributedString.DocumentType.rtf],documentAttributes: nil) {
        myLabel.attributedText = attributedString
 }

在这里我想向attributedString添加属性,例如 let boldAttributes: [NSAttributedString.Key: Any] = [.font: UIFont.boldSystemFont(ofSize: 14)] 并将这些属性应用到 attributedText

解决方法

如果你想将字体属性附加到现有属性,这个应该可以工作:

if let attributedString = try? NSMutableAttributedString(data: data,options: [.documentType: NSAttributedString.DocumentType.rtf],documentAttributes: nil) {
   var attrs = attributedString.attributes(at: 0,effectiveRange: nil)
   attrs[NSAttributedString.Key.font] = UIFont.boldSystemFont(ofSize: 14)
   attributedString.setAttributes(attrs,range: NSRange(location: 0,length: attributedString.length))
   myLabel.attributedText = attributedString
}