NSAttributedString添加自定义属性后丢失HTML标签格式问题
Fix: Custom Font Breaks HTML Formatting in UITextView
I’ve dealt with this exact frustration before! When you try to set a custom font on the entire attributed string generated from HTML parsing, you’re wiping out the special formatting (like the bold from <b> tags) that the HTML parser added. Here are two reliable ways to fix this:
Approach 1: Preserve Existing Formatting While Applying Custom Font
This method keeps all the HTML-derived styles (bold, line breaks, etc.) and only updates the base font, preserving any special font traits:
let htmlString = "<b>This is a title</b><br/>Another line." guard let attributedString = try? NSMutableAttributedString( data: htmlString.data(using: .utf8) ?? Data(), options: [ .documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue ], documentAttributes: nil ) else { return } // Define your custom font (make sure it's added to your project first!) let customFont = UIFont(name: "YourCustomFont-Regular", size: 16)! // Iterate through each range with font attributes attributedString.beginEditing() attributedString.enumerateAttribute(.font, in: NSRange(location: 0, length: attributedString.length)) { existingFontValue, range, _ in if let existingFont = existingFontValue as? UIFont { // Keep the existing font's traits (bold, italic) but swap in your custom font family let newDescriptor = existingFont.fontDescriptor.withFamily(customFont.familyName) let newFont = UIFont(descriptor: newDescriptor, size: customFont.pointSize) attributedString.addAttribute(.font, value: newFont, range: range) } else { // For text without existing font attributes, apply your custom font directly attributedString.addAttribute(.font, value: customFont, range: range) } } attributedString.endEditing() // Assign to your UITextView yourTextView.attributedText = attributedString
Approach 2: Embed Custom Font in the HTML String
If you have control over the HTML source, you can define the font directly in the HTML. This way, the parsed attributed string will already use your custom font without needing post-processing:
let customFontFamily = "YourCustomFont" let htmlString = """ <span style="font-family: '\(customFontFamily)'; font-size: 16px;"> <b>This is a title</b><br/>Another line. </span> """ guard let attributedString = try? NSAttributedString( data: htmlString.data(using: .utf8) ?? Data(), options: [ .documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue ], documentAttributes: nil ) else { return } yourTextView.attributedText = attributedString
Key Notes
- Double-check that your custom font is properly added to your project: add it to your target and register it in
Info.plistunderFonts provided by application. - Use Approach 1 if you can’t modify the original HTML string. Approach 2 is cleaner when you control the HTML input.
内容的提问来源于stack exchange,提问作者Godfather
相关产品推荐
相关产品推荐

