SwiftUI的.font()字体样式基本用法

254 阅读2分钟

在 SwiftUI 中,.font() 是一个常用的视图修饰符,用于控制文本的字体样式。以下是它的完整解析和用法指南:


一、基本定义

.font()View 的扩展方法,专门用于修饰 Text 或包含文本的视图(如 Button 的标签):

func font(_ font: Font?) -> some View

二、核心功能

1. 系统预设字体

SwiftUI 提供多种预设字体样式:

Text("Hello")
    .font(.largeTitle)    // 大标题(34pt)
    .font(.title)         // 标题(28pt)
    .font(.headline)      // 标题(加粗,17pt)
    .font(.subheadline)   // 子标题(15pt)
    .font(.body)          // 正文(默认,17pt)
    .font(.callout)       // 标注(16pt)
    .font(.footnote)      // 脚注(13pt)
    .font(.caption)       // 说明文字(12pt)
    .font(.caption2)      // 更小的说明文字(11pt)

2. 自定义字体

// 使用系统字体(动态类型支持)
Text("Custom")
    .font(.system(size: 20, weight: .bold, design: .rounded))

// 使用自定义字体(需先导入字体文件)
Text("Custom Font")
    .font(.custom("Avenir Next", size: 24))

3. 动态类型支持

自动适配系统字体大小设置:

.font(.body) // 会根据用户设置的辅助功能文字大小自动缩放

三、参数详解

参数类型说明示例
Font 枚举系统预设样式.font(.title)
size字号(CGFloat).system(size: 20)
weight字重(Font.Weight).weight(.black)
design字体设计(Font.Design).design(.monospaced)

▶ 字重选项(Font.Weight):

.ultraLight, .thin, .light, .regular, .medium, 
.semibold, .bold, .heavy, .black

▶ 字体设计(Font.Design):

.default    // 系统默认
.rounded    // 圆角字体
.monospaced // 等宽字体
.serif      // 衬线字体

四、高级用法

1. 组合使用

Text("组合样式")
    .font(.system(.title, design: .rounded).weight(.semibold))

2. 环境变量覆盖

VStack {
    Text("子视图文字")
}
.environment(\.font, .headline) // 影响所有子视图默认字体

3. 动态切换字体

@State private var isBold = false

Text("可切换")
    .font(isBold ? .body.bold() : .body)

五、注意事项

  1. 作用范围:仅对 Text 或包含文本的视图有效
  2. 性能优化:避免在频繁刷新的视图中动态创建字体(应提前定义)
  3. 自定义字体:需确保字体文件已添加到项目中并在 Info.plist 中声明

如果需要实现特定字体效果(如渐变文字),可以结合 .foregroundStyle 和其他修饰符使用。