如何将SwiftUI应用中的自定义字体共享至iOS设备
如何在SwiftUI应用中共享自定义字体到iOS设备系统层面
基础准备(你已完成的步骤回顾)
确保以下步骤已正确执行:
- 将字体文件(.ttf/.otf格式)添加到项目中,勾选「Copy items if needed」并确认Target Membership已选中当前应用。
- 在
Info.plist的Fonts provided by application字段中添加所有字体文件名(如CustomFont-Regular.ttf)。 - 在Xcode的「Capabilities」面板中添加「Fonts」,并激活「Install Fonts」和「Use Installed Fonts」选项。
核心:用CTFontManagerRegisterGraphicsFont注册字体到系统
要让字体共享给设备上的所有应用,必须通过CoreText框架的CTFontManagerRegisterGraphicsFontAPI完成系统级注册,以下是SwiftUI中的实现代码:
import CoreText import SwiftUI @main struct YourApp: App { init() { registerSystemWideFont() } var body: some Scene { WindowGroup { ContentView() } } private func registerSystemWideFont() { // 替换为你的字体文件名(不含扩展名)和格式 guard let fontURL = Bundle.main.url(forResource: "CustomFont-Regular", withExtension: "ttf") else { print("字体文件不存在") return } guard let dataProvider = CGDataProvider(url: fontURL as CFURL) else { print("无法读取字体数据") return } guard let cgFont = CGFont(dataProvider) else { print("无法加载CGFont对象") return } var registrationError: Unmanaged<CFError>? let isRegistered = CTFontManagerRegisterGraphicsFont(cgFont, ®istrationError) if !isRegistered { if let error = registrationError?.takeRetainedValue() { let errorMsg = CFErrorCopyDescription(error) ?? "未知错误" as CFString print("字体注册失败:\(errorMsg)") } } else { print("字体已成功注册到系统,其他应用可使用") } } }
关键说明
- 多字体文件处理:如果你的字体包含多个字重(如Bold、Italic),需要为每个字体文件单独执行上述注册逻辑,并确保
Info.plist中添加了所有文件名。 - 系统字体缓存刷新:注册完成后,部分应用可能需要重启才能识别到新字体,系统会在应用卸载时自动移除该字体。
- 格式兼容性:仅支持TrueType(.ttf)和OpenType(.otf)格式的字体,若字体文件损坏会导致注册失败。
- 应用内使用 vs 系统共享:普通应用内使用仅需
Info.plist注册即可,但系统级共享必须通过CTFontManagerRegisterGraphicsFont完成,这是系统开放的全局字体注册入口。
内容的提问来源于stack exchange,提问作者Lorenzo97Ben
相关产品推荐
相关产品推荐

