iOS设备适配字体添加ClashGrotesk遇可选值解包错误求解决
解决iOS自定义字体ClashGrotesk的可选值解包问题并保留设备适配逻辑
先排查自定义字体的导入与名称正确性
解包错误的核心原因是系统找不到你指定的字体,先搞定这一步:
- 把ClashGrotesk的字体文件(.otf/.ttf)拖进项目,勾选Target Membership确保归属当前主工程
- 打开Info.plist,添加
Fonts provided by application数组,将所有字体的完整文件名(比如ClashGrotesk-Semibold.otf)逐个添加进去 - 验证字体的真实系统名称:运行以下代码打印所有可用字体,找到ClashGrotesk对应的真实名称,确保枚举里的rawValue和这个完全一致(有时候字体文件名和系统识别名不一样)
for family in UIFont.familyNames { print("Family: \(family)") for name in UIFont.fontNames(forFamilyName: family) { print(" Font: \(name)") } }
修改代码:保留适配逻辑+安全处理字体加载
把原来的设备适配逻辑(dp扩展)保留,同时修改UIFont扩展,避免强制解包,增加回退逻辑:
extension UIFont { public enum ClashGroteskType: String { // 替换成上面打印出的真实字体名称 case semibold = "ClashGrotesk-Semibold" case regular = "ClashGrotesk-Regular" case medium = "ClashGrotesk-Medium" case light = "ClashGrotesk-Light" case extralight = "ClashGrotesk-Extralight" case bold = "ClashGrotesk-Bold" } class func appFont( type: ClashGroteskType = .semibold, ofSize size: CGFloat = UIFont.systemFontSize ) -> UIFont { // 尝试加载自定义字体,失败则回退到对应权重的系统字体 guard let customFont = UIFont(name: type.rawValue, size: size.dp) else { let weight: UIFont.Weight switch type { case .extralight: weight = .ultraLight case .light: weight = .light case .regular: weight = .regular case .medium: weight = .medium case .semibold: weight = .semibold case .bold: weight = .bold } return UIFont.systemFont(ofSize: size.dp, weight: weight) } return customFont } } // 保留原有的设备适配扩展 extension CGFloat { var dp: CGFloat { let width = UIScreen.main.bounds.width let device = UIScreen.main.traitCollection.userInterfaceIdiom if device == .phone { if width <= 375 { return self * 0.60 } else if width <= 414 { return self } } else if device == .pad { if width <= 1024 { return self * 2.0 } } return self } }
调用方式
和之前的调用逻辑完全兼容,也可以指定字体类型:
// 默认使用ClashGrotesk-Semibold cell.stepsLabel.font = UIFont.appFont(ofSize: 32) // 指定其他字体类型 cell.titleLabel.font = UIFont.appFont(type: .regular, ofSize: 16)
内容的提问来源于stack exchange,提问作者Krunal Kathiriya
相关产品推荐
相关产品推荐

