【问题标题】:Data to attributedString with font attributes Swift具有字体属性Swift的属性字符串数据
【发布时间】:2021-02-10 21:45:51
【问题描述】:

我有一个 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
 }

在这里,我想将属性添加到属性字符串中,例如 let boldAttributes: [NSAttributedString.Key: Any] = [.font: UIFont.boldSystemFont(ofSize: 14)] 并将这些属性应用于属性文本

【问题讨论】:

  • 您是要舍弃原有的属性(字体)还是只将字体加粗并改变其大小?
  • 我只是想让字体变粗并改变它的大小

标签: swift nsattributedstring


【解决方案1】:

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

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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-10
    • 2011-04-12
    • 1970-01-01
    • 2015-10-17
    • 1970-01-01
    • 2015-04-14
    相关资源
    最近更新 更多