Swift添加字体到项目中

  1. 下载字体,导入到项目文件夹。

  2. 项目Info添加Fonts provided by application的item为字体文件名"xxx.ttf"。

  3. 打印出所有字体名,找到导入的字体文件对应不同weight的字体。如果还是找不到,我也不知道怎么解决。

Swift 复制代码
    for family in UIFont.familyNames.sorted() {
        for fontName in UIFont.fontNames(forFamilyName: family).sorted() {
            print(fontName)
        }
    }
  1. 针对不同weight返回不同字体。
Swift 复制代码
func getEnglishFont(ofSize size: CGFloat, weight: UIFont.Weight) -> UIFont {
        var font: UIFont? = nil
        
        switch weight {
        case .ultraLight:
            font = UIFont(name: "KumbhSans-Regular_ExtraLight", size: size)
        case .thin:
            font = UIFont(name: "KumbhSans-KumbhSans-Regular_Thin", size: size)
        case .light:
            font = UIFont(name: "KumbhSans-Regular_Light", size: size)
        case .regular:
            font = UIFont(name: "KumbhSans-Regular", size: size)
        case .medium:
            font = UIFont(name: "KumbhSans-Regular_Medium", size: size)
        case .semibold:
            font = UIFont(name: "KumbhSans-Regular_SemiBold", size: size)
        case .bold:
            font = UIFont(name: "KumbhSans-Regular_Bold", size: size)
        case .heavy:
            font = UIFont(name: "KumbhSans-Regular_ExtraBold", size: size)
        case .black:
            font = UIFont(name: "KumbhSans-Regular_Black", size: size)
        default:
            print("default font")
            font = UIFont(name: "KumbhSans-Regular", size: size)
        }

        var nonEmptyFont: UIFont = UIFont.systemFont(ofSize: size, weight: weight)
        if let tmpFont = font {
            nonEmptyFont = tmpFont
        } else {
            print("使用默认字体")
        }
        
        return nonEmptyFont
    }
相关推荐
lightqjx9 分钟前
【C++】unordered系列的封装
开发语言·c++·stl·unordered系列
Haha_bj14 分钟前
Flutter ——flutter_screenutil 屏幕适配
android·ios
zh_xuan24 分钟前
kotlin lazy委托异常时执行流程
开发语言·kotlin
Haha_bj32 分钟前
Flutter ——device_info_plus详解
android·flutter·ios
阿猿收手吧!41 分钟前
【C++】string_view:高效字符串处理指南
开发语言·c++
玄同7651 小时前
我的 Trae Skill 实践|使用 UV 工具一键搭建 Python 项目开发环境
开发语言·人工智能·python·langchain·uv·trae·vibe coding
Yorlen_Zhang1 小时前
Python Tkinter Text 控件完全指南:从基础编辑器到富文本应用
开发语言·python·c#
lxl13071 小时前
C++算法(1)双指针
开发语言·c++
不绝1912 小时前
C#进阶:预处理指令/反射,Gettype,Typeof/关键类
开发语言·c#
无小道2 小时前
Qt-qrc机制简单介绍
开发语言·qt