UIFont+Ex.swift 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. //
  2. // UIFont+Ex.swift
  3. // TSLiveWallpaper
  4. //
  5. // Created by 100Years on 2024/12/20.
  6. //
  7. public typealias FontName = String
  8. public extension FontName {
  9. static public let PingFangSC = "PingFangSC"
  10. static public let CherryBombOneRegular = "Cherry Bomb One"
  11. static public let PoppinsBoldItalic = "Poppins-BoldItalic"
  12. static public let CoveredByYourGrace = "Covered By Your Grace"
  13. }
  14. public extension UIFont {
  15. class public func font(name: FontName = .PingFangSC, size: CGFloat, weight: UIFont.Weight = .regular) -> UIFont {
  16. guard !name.isEmpty,
  17. let _ = UIFont(name: name, size: size) else {
  18. return UIFont.systemFont(ofSize: size, weight: weight)
  19. }
  20. var finalFontName = name
  21. // print("FontName name = \(name)")
  22. let fontNames = UIFont.fontNames(forFamilyName: name)
  23. switch weight {
  24. case .light://细体 300
  25. if let aName = fontNames.first(where: { $0.lowercased().hasSuffix("-light") || $0.lowercased().hasSuffix("_light") }) {
  26. finalFontName = aName
  27. }
  28. case .medium://中黑体 500
  29. if let aName = fontNames.first(where: { $0.lowercased().hasSuffix("-medium") || $0.lowercased().hasSuffix("_medium") }) {
  30. finalFontName = aName
  31. }
  32. case .bold:// 粗体 700
  33. if let aName = fontNames.first(where: { $0.lowercased().hasSuffix("-bold") || $0.lowercased().hasSuffix("_bold") }) {
  34. finalFontName = aName
  35. }
  36. case .semibold://半粗体 600
  37. if let aName = fontNames.first(where: { $0.lowercased().hasSuffix("-semibold") || $0.lowercased().hasSuffix("_semibold") }) {
  38. finalFontName = aName
  39. }
  40. case .heavy: //粗黑体 800
  41. if let aName = fontNames.first(where: { $0.lowercased().hasSuffix("-heavy") || $0.lowercased().hasSuffix("_heavy") }) {
  42. finalFontName = aName
  43. }
  44. case .black: // 黑体 900
  45. if let aName = fontNames.first(where: { $0.lowercased().hasSuffix("-black") || $0.lowercased().hasSuffix("_black") }) {
  46. finalFontName = aName
  47. }
  48. default:
  49. break
  50. }
  51. return UIFont(name: finalFontName, size: size)!
  52. }
  53. }