Swift添加自定义字体

1. 在 Xcode 中添加自定义字体

首先,你需要将自定义字体文件(如 .ttf.otf 文件)添加到项目中。

  1. 将字体文件拖放到项目的资源管理器中,确保选中了 "Copy items if needed"
  2. 打开 Info.plist 文件,添加一个新的键 Fonts provided by application(也叫 UIAppFonts),然后将字体文件的名称(包括扩展名 .ttf.otf)添加到这个数组中。
XML 复制代码
<key>UIAppFonts</key>
<array>
    <string>YourCustomFont.ttf</string>
</array>

2. 使用自定义字体

确保字体文件已经成功添加到项目中后,你可以在代码中为 UILabel、UITextView 或 UIButton 设置该字体。

Swift 复制代码
<key>UIAppFonts</key>
<array>
    <string>YourCustomFont.ttf</string>
</array>

注意,YourCustomFontName 是字体的实际名称,而不是字体文件的名称。你可以通过以下代码来检查你项目中的所有可用字体名称:

Swift 复制代码
<key>UIAppFonts</key>
<array>
    <string>YourCustomFont.ttf</string>
</array>

通过运行这段代码,你可以找到自定义字体的正确名称,并在应用程序中使用它。

3. 在 Storyboard 或 Interface Builder 中设置自定义字体

  1. 选中 UILabel 或 UIButton 等控件。
  2. 在右侧的属性检查器(Attributes Inspector)中找到字体设置项。
  3. 点击字体选择器,选择 "Custom" 并从下拉列表中选择你添加的自定义字体。

这样,你的 UILabel、UITextView、UIButton 等控件就可以使用自定义字体了。

相关推荐
HarderCoder2 小时前
Swift 6 并发时代,如何优雅地“抢救”你的单例?
swift
zhangmeng2 小时前
FlutterBoost在iOS26真机运行崩溃问题
flutter·app·swift
HarderCoder2 小时前
SwiftUI 踩坑记:onAppear / task 不回调?90% 撞上了“空壳视图”!
swift
HarderCoder2 小时前
@isolated(any) 深度解析:Swift 并发中的“隔离追踪器”
swift
大熊猫侯佩6 小时前
桃花岛 Xcode 构建秘籍:Swift 中的 “Feature Flags” 心法
app·xcode·swift
用户097 小时前
SwiftUI Charts 函数绘图完全指南
ios·swiftui·swift
YungFan7 小时前
iOS26适配指南之UIColor
ios·swift
HarderCoder8 小时前
Swift 6.2 新特性 `@concurrent` 完全导读
swift
HarderCoder9 小时前
Swift 里的“橡皮擦”与“标签”——搞懂 existentials 与 primary associated type
swift
权咚1 天前
阿权的开发经验小集
git·ios·xcode