У меня есть HTML, и он был преобразован в AttributedString. Теперь мне нужно изменить шрифт сгенерированной строки Attributed, но мне трудно сохранить стиль (полужирный, курсив или обычный).
Я нашел решение, но проблема в том, что я не знаю, как его использовать. Они используют 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()
}
}
Решение Manmal:
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()
}
}