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

SwiftUI中AttributedString的使用方法:Text组件无可用API怎么办?

在SwiftUI中使用AttributedString的解决方案

嘿,这个问题我之前折腾过,其实现在SwiftUI已经有几种靠谱的方式来处理AttributedString了,我给你整理三个实用方案,覆盖不同场景和版本需求:

方案1:直接用Text原生支持(iOS 15+ / macOS 12+ / 其他对应版本)

从iOS 15开始,SwiftUI的Text组件已经原生支持AttributedString了,这是最直接的方式。你可以先构建好带有各种样式的AttributedString,直接传给Text就行。

示例代码:

import SwiftUI

struct ContentView: View {
    var body: some View {
        // 用Markdown快速生成富文本
        let markdownAttrString = try! AttributedString(markdown: "**加粗文本** 普通文本 *斜体文本*")
        
        // 手动自定义样式
        var customAttrString = AttributedString("自定义样式文本")
        customAttrString.font = .system(size: 18, weight: .semibold)
        customAttrString.foregroundColor = .blue
        customAttrString.underlineStyle = Text.LineStyle(pattern: .dash, color: .red)
        
        VStack(spacing: 20) {
            Text(markdownAttrString)
            Text(customAttrString)
        }
    }
}

方案2:兼容低版本(用UIViewRepresentable包装UILabel)

如果你的项目需要支持iOS 15以下的版本,那就可以通过UIViewRepresentable把UIKit的UILabel包装成SwiftUI组件——毕竟UILabel一直都支持NSAttributedString(Swift的AttributedString和NSAttributedString还能互相转换)。

示例代码:

import SwiftUI

struct AttributedText: UIViewRepresentable {
    var attributedString: NSAttributedString
    
    func makeUIView(context: Context) -> UILabel {
        let label = UILabel()
        label.numberOfLines = 0 // 支持多行显示
        label.lineBreakMode = .byWordWrapping
        return label
    }
    
    func updateUIView(_ uiView: UILabel, context: Context) {
        uiView.attributedText = attributedString
    }
}

// 使用示例
struct ContentView: View {
    var body: some View {
        let nsAttrString = NSAttributedString(
            string: "兼容低版本的富文本",
            attributes: [
                .font: UIFont.systemFont(ofSize: 16, weight: .bold),
                .foregroundColor: UIColor.purple,
                .underlineStyle: NSUnderlineStyle.single.rawValue
            ]
        )
        
        AttributedText(attributedString: nsAttrString)
            .padding()
    }
}

// Swift AttributedString转NSAttributedString的方式:
// let swiftAttrString = AttributedString("测试文本")
// let nsAttrString = NSAttributedString(swiftAttrString)

方案3:SwiftUI原生样式拼接(适合简单场景)

如果你的富文本需求比较简单,不需要复杂的AttributedString,也可以直接用SwiftUI的Text组件拼接不同样式的片段,这种方式不用依赖AttributedString,代码更直观。

示例代码:

import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("这是")
            .font(.body)
            + Text("加粗的")
            .font(.headline)
            .bold()
            + Text("文本,还有")
            + Text("红色的")
            .foregroundColor(.red)
            + Text("部分")
    }
}

根据你的项目版本和需求选对应的方案就行,现在SwiftUI对富文本的支持已经比早期完善很多啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:00:24