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

Swift Playgrounds 4.2.1(.swiftpm项目)中如何使用自定义字体?

SwiftPM格式SwiftUI Playground加载自定义OTF字体解决方案

一、正确配置字体资源

  • 将你的.otf字体文件拖入SwiftPM项目目录,建议放在模块的Resources文件夹下(比如Sources/YourPlaygroundModule/Resources)
  • 选中字体文件,在Xcode右侧检查器中,确保Target Membership勾选当前Playground模块
  • 修改Package.swift,在对应target的配置中添加资源处理规则,让SwiftPM正确打包字体:
    targets: [
        .target(
            name: "YourPlaygroundModule",
            dependencies: [],
            resources: [
                .process("Resources/YourFont.otf") // 路径需与实际文件位置匹配
            ]
        ),
        // 其他target...
    ]
    

二、手动注册字体(核心步骤)

由于SwiftPM项目没有Info.plist,无法自动注册字体,需手动通过CoreText接口注册:

import UIKit // macOS项目替换为AppKit

func registerCustomFont() {
    // 从模块Bundle中获取字体文件URL
    guard let fontURL = Bundle.module.url(forResource: "YourFont", withExtension: "otf"),
          // 读取字体数据
          let fontData = try? Data(contentsOf: fontURL),
          // 创建CG字体数据提供者
          let dataProvider = CGDataProvider(data: fontData as CFData),
          // 创建CG字体实例
          let cgFont = CGFont(dataProvider) else {
        fatalError("无法读取自定义字体文件")
    }
    
    // 注册字体到系统
    var registrationError: Unmanaged<CFError>?
    guard CTFontManagerRegisterGraphicsFont(cgFont, &registrationError) else {
        if let error = registrationError?.takeRetainedValue() {
            fatalError("字体注册失败:\(error.localizedDescription)")
        }
        fatalError("字体注册失败,未知错误")
    }
}

// 在Playground启动时执行注册
registerCustomFont()

三、使用自定义字体

用你已确认的PostScript名称创建SwiftUI Font:

import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("自定义字体测试")
            .font(Font.custom("YourFontPostScriptName", size: 24))
    }
}

// Playground预览
ContentView()
    .previewLayout(.sizeThatFits)

四、常见问题排查

  • 核对Package.swift中的资源路径,确保和字体文件的实际位置完全一致
  • 清理Playground的Derived Data(Xcode菜单:Product → Clean Build Folder)后重新运行
  • 再次验证字体PostScript名称:可通过Mac字体册选中字体,查看「信息」面板中的PostScript名称

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 03:42:32