You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift实现JSON文本富文本化:为Label添加粗体/斜体样式

解析JSON中的自定义标签并渲染富文本

首先,你需要先解析JSON里带<b>/<i>标签的文本,把这些标签转换成对应的富文本样式——因为普通的Label控件默认不识别HTML标签,得手动处理标签并生成富文本。下面分步骤给你实现方案,还有替代思路:

一、解析自定义标签生成富文本(以iOS Swift为例)

核心思路是用正则匹配出<b>/</b>、<i>/</i>包裹的文本段,然后给这些段落设置对应的字体样式,最后生成NSAttributedString赋值给Label。

这里是实现代码:

func attributedText(from taggedText: String) -> NSAttributedString {
    let mutableAttributedString = NSMutableAttributedString(string: taggedText)
    let baseFont = UIFont.systemFont(ofSize: 16)
    
    // 处理粗体标签
    let boldRegex = try! NSRegularExpression(pattern: "<b>(.*?)</b>", options: .dotMatchesLineSeparators)
    let boldMatches = boldRegex.matches(in: taggedText, range: NSRange(taggedText.startIndex..., in: taggedText))
    
    for match in boldMatches.reversed() {
        let contentRange = match.range(at: 1)
        let boldFont = UIFont.boldSystemFont(ofSize: 16)
        mutableAttributedString.addAttribute(.font, value: boldFont, range: contentRange)
        // 移除<b>和</b>标签
        mutableAttributedString.deleteCharacters(in: match.range(at: 0))
    }
    
    // 处理斜体标签
    let italicRegex = try! NSRegularExpression(pattern: "<i>(.*?)</i>", options: .dotMatchesLineSeparators)
    let italicMatches = italicRegex.matches(in: mutableAttributedString.string, range: NSRange(mutableAttributedString.string.startIndex..., in: mutableAttributedString.string))
    
    for match in italicMatches.reversed() {
        let contentRange = match.range(at: 1)
        let italicFont = UIFont.italicSystemFont(ofSize: 16)
        mutableAttributedString.addAttribute(.font, value: italicFont, range: contentRange)
        // 移除<i>和</i>标签
        mutableAttributedString.deleteCharacters(in: match.range(at: 0))
    }
    
    return mutableAttributedString
}

// 使用示例:
let jsonText = "this is my text <b>bold</b> or <i>italic</i>"
myLabel.attributedText = attributedText(from: jsonText)

如果是Android平台,可以用SpannableString结合正则来处理,思路类似:匹配标签,给对应文本段设置StyleSpan(Typeface.BOLD)或StyleSpan(Typeface.ITALIC),然后移除标签。

二、其他从JSON实现文本粗体的替代方案

除了自定义HTML标签,还有几种更灵活的方案:

  • 用Markdown语法存储文本:在JSON里写**bold**和*italic*,然后用第三方库(比如iOS的Down、Android的Markwon)把Markdown转换成富文本。这种方案可读性更强,也支持更多样式(比如下划线、列表)。
  • JSON直接存储富文本结构:把文本拆分成多个片段,每个片段包含内容和样式标记,比如:
    {
      "textSegments": [
        {"content": "this is my text ", "style": "normal"},
        {"content": "bold", "style": "bold"},
        {"content": " or ", "style": "normal"},
        {"content": "italic", "style": "italic"}
      ]
    }
    
    解析时直接遍历片段,给每个片段设置对应样式后拼接成富文本,这种方案最灵活,容易扩展更多样式(比如颜色、字号)。
  • 使用原生富文本的JSON格式:比如iOS的NSAttributedString可以直接序列化/反序列化为JSON格式(需要用NSKeyedArchiver转成Data再转成JSON,或者用第三方库),Android的SpannableString也有对应的序列化方案,这种方案不需要手动解析标签,直接还原富文本。

三、注意事项

如果你的Label支持加载HTML(比如iOS的UILabel可以通过NSAttributedString.DocumentType.html直接解析HTML),也可以尝试直接把带<b>/<i>的文本转成HTML富文本:

if let data = jsonText.data(using: .utf8) {
    let attributedText = try! NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
    myLabel.attributedText = attributedText
}

但这种方法可能会引入默认的HTML样式(比如字体、行高),需要额外调整,而且性能比手动解析标签稍差。

内容的提问来源于stack exchange,提问作者user291334

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:31:50