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

SwiftUI中如何为AttributedString生成的Markdown文本添加换行

Swift中AttributedString解析Markdown换行无效的解决方法

当用AttributedString(markdown:)解析包含\n的文本时,默认不会将单个换行符识别为换行(这符合标准Markdown规则,标准Markdown需要两个空格加换行才会触发换行),而直接传入字符串的Text组件会直接解析\n为换行,这就是两者表现不同的原因。

下面是几种可行的解决方法:

  • 方法一:使用标准Markdown换行语法
    在换行前添加两个空格,让AttributedString正确识别换行:

    struct MarkdownText: View {
        var body: some View {
            VStack {
                Text("I am **bold**.\nI am *italic*.")
                Text(try! AttributedString(markdown: "I am **bold**.  \nI am *italic*."))
            }
        }
    }
    
  • 方法二:自定义Markdown解析选项
    通过设置MarkdownParsingOptions,让解析器将单个\n识别为换行符:

    struct MarkdownText: View {
        var body: some View {
            VStack {
                Text("I am **bold**.\nI am *italic*.")
                
                let options = AttributedString.MarkdownParsingOptions(
                    allowsExtendedAttributes: true,
                    interlineSeparator: .newline
                )
                let attrString = try! AttributedString(markdown: "I am **bold**.\nI am *italic*.", options: options)
                Text(attrString)
            }
        }
    }
    
  • 方法三:使用HTML换行标签
    AttributedString支持解析HTML格式的Markdown,直接用<br>标签实现换行:

    struct MarkdownText: View {
        var body: some View {
            VStack {
                Text("I am **bold**.\nI am *italic*.")
                Text(try! AttributedString(markdown: "I am **bold**.<br>I am *italic*."))
            }
        }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 18:52:09