如何将 AttributedString 转换为 NSMutableString Swift?



我有HTML,并被转换为AttributedString。现在,我需要更改生成的属性字符串的字体,但我很难保留样式(粗体、斜体或常规(。

我找到了一个解决方案,但问题是我不知道如何使用它。他们使用 NSMutableAttributedString 作为扩展。我在底部粘贴了我的代码如何转换和假定的解决方案。

谢谢。

extension String {
var htmlToAttributedString: NSAttributedString? {
guard let data = data(using: .utf8) else { return NSAttributedString() }
do {
return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
return NSAttributedString()
}
}
}



import Foundation
struct Service: Codable {
var id: Int
var name: String?
var price: String?
var description: String?
var subtitle: String?
var bodyPreview: String?
var featuredImage: String? // For FindAll
var imageList: [String]? // For FindByID
private enum CodingKeys: String, CodingKey {
case id
case name
case price
case subtitle
case description
case bodyPreview = "body_preview"
case featuredImage = "featured_image_url"
case imageList = "images_url"
}
}

class ServiceDetailViewController: UIViewController {

private var service: Service?
private func showServiceDetails() {
detailLabel.attributedText = service?.description?.htmlToAttributedString
collectionView.reloadData()
startCollectionViewTimer()
}
}

曼马尔的解决方案:

extension NSMutableAttributedString {
func setFontFace(font: UIFont, color: UIColor? = nil) {
beginEditing()
self.enumerateAttribute(
.font,
in: NSRange(location: 0, length: self.length)
) { (value, range, stop) in
if let f = value as? UIFont,
let newFontDescriptor = f.fontDescriptor
.withFamily(font.familyName)
.withSymbolicTraits(f.fontDescriptor.symbolicTraits) {
let newFont = UIFont(
descriptor: newFontDescriptor,
size: font.pointSize
)
removeAttribute(.font, range: range)
addAttribute(.font, value: newFont, range: range)
if let color = color {
removeAttribute(
.foregroundColor,
range: range
)
addAttribute(
.foregroundColor,
value: color,
range: range
)
}
}
}
endEditing()
}
}

关于反向转换,请参阅爱斯基摩人的回答 https://developer.apple.com/forums/thread/682431

let mutableAttributedString = NSMutableAttributedString("… something …")
let attributedString = try? AttributedString(mutableAttributedString, including: .foundation)

let attriString = NSAttributedString(string:"attriString", attributes: [NSAttributedString.Key.foregroundColor: UIColor.lightGray, NSAttributedString.Key.font: AttriFont](

您可以简单地创建一个类似的扩展来返回一个可变的属性字符串:

extension String {
var htmlToMutableAttributedString: NSMutableAttributedString? {
do {
return try .init(data: Data(utf8), options: [.documentType:  NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
print(error)
return nil
}
}
}

最新更新