如何让NSMutableAttributedString转换为HTML的H1元素?
问题描述
我通过以下Swift代码创建NSAttributedString:
let titleAttributes: [NSAttributedString.Key: Any] = [ .font: UIFont.systemFont(ofSize: 24), .foregroundColor: UIColor.black, .paragraphStyle: { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.headIndent = 1.0 return paragraphStyle }() ] let attributedText = NSMutableAttributedString(string: "H1 title", attributes: titleAttributes)
再通过这段代码将其转为HTML:
let htmlData = try! attributedText.data(from: NSRange(location: 0, length: attributedText.length), documentAttributes: [ .documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue ]) let htmlString = String(data: htmlData, encoding: .utf8)!
转换后得到的HTML结构是:
<p class="p1"><span class="s1">My Title</span></p>
默认会生成p和span标签,请问有没有办法让这个NSAttributedString转换为HTML的H1元素?
解决方案
方法一:利用headingLevel属性(iOS 15+/macOS 12+)
苹果在iOS 15和macOS 12之后新增了NSAttributedString.Key.headingLevel属性,直接指定标题层级就能让HTML转换生成对应的H1-H6标签。
修改属性字典,添加.headingLevel键并设置值为1(对应H1,2对应H2,以此类推):
let titleAttributes: [NSAttributedString.Key: Any] = [ .font: UIFont.systemFont(ofSize: 24), .foregroundColor: UIColor.black, .headingLevel: 1, // 指定为H1层级 .paragraphStyle: { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.headIndent = 1.0 return paragraphStyle }() ] let attributedText = NSMutableAttributedString(string: "H1 title", attributes: titleAttributes)
重新执行转换代码后,生成的HTML会变成:
<h1 class="h1"><span class="s1">H1 title</span></h1>
方法二:兼容旧系统的字符串替换方案
如果需要支持iOS 15之前的版本,无法通过原生API直接生成H1标签,只能在转换完成后手动修改HTML字符串:
// 先完成原有的HTML转换 let htmlData = try! attributedText.data(from: NSRange(location: 0, length: attributedText.length), documentAttributes: [ .documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue ]) var htmlString = String(data: htmlData, encoding: .utf8)! // 替换p标签为h1标签 htmlString = htmlString.replacingOccurrences(of: "<p class=\"p1\">", with: "<h1>") htmlString = htmlString.replacingOccurrences(of: "</p>", with: "</h1>")
注意:这里的class="p1"是系统默认生成的类名,实际转换时如果类名不同,需要对应调整替换规则。
内容的提问来源于stack exchange,提问作者mahan
相关产品推荐
相关产品推荐

