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

SwiftUI中如何默认全局使用Apple SF Rounded字体?

如何在SwiftUI中全局默认使用SF Rounded字体?

下面提供几种实用的实现方式,按需选择:

1. 扩展Font类型,快速调用rounded字体

先给Font写个扩展,封装带.rounded设计的字体创建逻辑:

extension Font {
    /// 创建带SF Rounded设计的字体
    /// - Parameters:
    ///   - style: 系统文本样式(如.title2、.body)
    ///   - weight: 字重,默认常规
    static func rounded(_ style: Font.TextStyle, weight: Font.Weight = .regular) -> Font {
        .system(style, design: .rounded, weight: weight)
    }

    // 也可以直接预定义常用样式,省去每次传参
    static let roundedTitle2Semibold = Font.system(.title2, design: .rounded, weight: .semibold)
    static let roundedBody = Font.system(.body, design: .rounded)
}

使用时直接调用:

Text("示例文本")
    .font(.rounded(.title2, weight: .semibold))
// 或者用预定义样式
Text("预定义样式")
    .font(.roundedTitle2Semibold)

2. 通过环境变量全局设置默认字体

在App的根视图或入口处,给整个应用注入默认的rounded字体环境:

@main
struct YourApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
                // 设置全局默认body样式为SF Rounded
                .environment(\.font, .rounded(.body))
        }
    }
}

这样所有未单独设置字体的文本,都会自动使用SF Rounded的body样式。如果需要覆盖不同的系统文本样式(如标题、副标题),可以自定义环境键来分别配置。

3. 自定义ViewModifier,全局统一应用

如果需要更灵活的全局控制(比如针对不同文本样式单独设置),可以写一个ViewModifier:

struct RoundedFontsModifier: ViewModifier {
    func body(content: Content) -> some View {
        content
            // 给默认文本设置rounded body
            .environment(\.font, .rounded(.body))
            // 针对标题样式单独设置
            .environment(\.titleFont, .rounded(.title, weight: .bold))
            .environment(\.headlineFont, .rounded(.headline))
    }
}

// 自定义环境键,用于处理不同文本样式
private struct TitleFontKey: EnvironmentKey {
    static let defaultValue: Font = .rounded(.title)
}

private struct HeadlineFontKey: EnvironmentKey {
    static let defaultValue: Font = .rounded(.headline)
}

extension EnvironmentValues {
    var titleFont: Font {
        get { self[TitleFontKey.self] }
        set { self[TitleFontKey.self] = newValue }
    }
    
    var headlineFont: Font {
        get { self[HeadlineFontKey.self] }
        set { self[HeadlineFontKey.self] = newValue }
    }
}

// 给View添加便捷调用方法
extension View {
    func useRoundedFonts() -> some View {
        modifier(RoundedFontsModifier())
    }
}

然后在根视图应用这个Modifier:

ContentView()
    .useRoundedFonts()

之后在子视图中可以直接读取自定义环境字体:

Text("标题文本")
    .font(Environment(\.titleFont))

注意事项

部分系统控件(如NavigationBar的默认标题)可能不会自动遵循环境字体,需要单独设置:

.navigationBarTitleDisplayMode(.inline)
.toolbar {
    ToolbarItem(placement: .principal) {
        Text("导航标题")
            .font(.rounded(.title))
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 17:56:12