iOS swift-markdown 自定文字颜色
2025年6月28日 15:30
最近在做AI的产品,用到了Markdown渲染,其中有一个变态的需求 需要对一段文字的某几个字颜色做特殊处理
效果

思路
Inline
其实实现思路很简单,一句话说完,就是自定义一个inline语法,然后实现MarkupVisitor
协议的visitInlineAttributes
方法
// https://docs.xiaohongshu.com/doc/35cfb0f7715be75c4e12f67ce3982a0b
public mutating func visitInlineAttributes(_ attributes: InlineAttributes) -> NSAttributedString {
let result = NSMutableAttributedString()
for child in attributes.children {
result.append(visit(child))
}
if attributes.attributes.hasPrefix("Color#") {
let color = attributes.attributes.components(separatedBy: "#").last ?? "FFFFFF"
result.addAttribute(.foregroundColor, value: UIColor.argb("#\(color)"))
}
return result
}
// let markdownText = """Opening ^[**这是一段加粗自定义颜色文字**](Color#333333) paragraph, with an ordered list of autumn leaves I found"""
Block
如果你是非inline的文字,而是一块,可以考虑使用该接口visitBlockDirective
// https://docs.xiaohongshu.com/doc/35cfb0f7715be75c4e12f67ce3982a0b
public mutating func visitBlockDirective(_ blockDirective: BlockDirective) -> NSAttributedString {
let result = NSMutableAttributedString()
for child in blockDirective.children {
result.append(visit(child))
}
if blockDirective.name.hasPrefix("Color#") {
let color = blockDirective.name.components(separatedBy: "#").last ?? "FFFFFF"
result.addAttribute(.foregroundColor, value: UIColor.argb("#\(color)"))
}
return result
}
// let markdownText = """Opening @Color#333333 { **这是一段加粗自定义颜色文字** } paragraph, with an ordered list of autumn leaves I found"""