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

如何修改通过Markdown生成的AttributedString中样式文本的外观

报错根因

两个报错本质上是同一个问题导致的:stronglyEmphasized属于平台相关的属性作用域,没有明确上下文的情况下编译器无法定位到该成员,进而无法完成泛型类型推断。
另外你的代码逻辑存在额外问题:使用replace方法会直接移除原有的stronglyEmphasized属性,会丢失你想要保留的加粗效果。

解决步骤

  1. 先确认你使用的UI框架,导入对应依赖后明确指定属性的作用域:
    • SwiftUI 环境对应 AttributeScopes.SwiftUIAttributes
    • UIKit 环境对应 AttributeScopes.UIKitAttributes
    • AppKit 环境对应 AttributeScopes.AppKitAttributes
  2. 不要替换原有强调属性,直接在匹配到的属性容器中追加前景色配置即可保留加粗效果。
  3. 额外注意:Markdown 语法中*包裹的内容对应普通强调(emphasized,默认表现为斜体),**包裹的内容才对应粗体强调(stronglyEmphasized),如果你的测试内容用的是单星号需要对应调整属性名称。

正确代码示例(SwiftUI环境)

import SwiftUI
import Foundation

let attributedString = try! AttributedString(markdown: "This string **has** some markdown")
let transformed = attributedString.transformingAttributes(\.swiftUI.stronglyEmphasized) { attribute in
    attribute.container.foregroundColor = .red
}

正确代码示例(UIKit环境)

import UIKit
import Foundation

let attributedString = try! AttributedString(markdown: "This string **has** some markdown")
let transformed = attributedString.transformingAttributes(\.uiKit.stronglyEmphasized) { attribute in
    attribute.container.foregroundColor = UIColor.red
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 05:45:11