数据到具有字体属性的 attributedString Swift
Data to attributedString with font attributes Swift
我有一个 RTF 文件,我可以通过它获取内容作为数据(我希望它位于数据中以便在代码的其他地方使用它)。但是,我想在分配给标签之前将样式添加到 attributedString 之类的字体。我对如何在下面的代码中应用这些属性感到震惊。请建议我如何实现同样的目标。这是我的代码
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
}
我有一个 RTF 文件,我可以通过它获取内容作为数据(我希望它位于数据中以便在代码的其他地方使用它)。但是,我想在分配给标签之前将样式添加到 attributedString 之类的字体。我对如何在下面的代码中应用这些属性感到震惊。请建议我如何实现同样的目标。这是我的代码
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
}