UIFont+Ex.swift 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. }
  11. public extension UIFont {
  12. class public func font(name: FontName = .PingFangSC, size: CGFloat, weight: UIFont.Weight = .regular) -> UIFont {
  13. guard !name.isEmpty,
  14. let _ = UIFont(name: name, size: size) else {
  15. return UIFont.systemFont(ofSize: size, weight: weight)
  16. }
  17. var finalFontName = name
  18. let fontNames = UIFont.fontNames(forFamilyName: name)
  19. switch weight {
  20. case .light://细体 300
  21. if let aName = fontNames.first(where: { $0.lowercased().hasSuffix("-light") || $0.lowercased().hasSuffix("_light") }) {
  22. finalFontName = aName
  23. }
  24. case .medium://中黑体 500
  25. if let aName = fontNames.first(where: { $0.lowercased().hasSuffix("-medium") || $0.lowercased().hasSuffix("_medium") }) {
  26. finalFontName = aName
  27. }
  28. case .bold:// 粗体 700
  29. if let aName = fontNames.first(where: { $0.lowercased().hasSuffix("-bold") || $0.lowercased().hasSuffix("_bold") }) {
  30. finalFontName = aName
  31. }
  32. case .semibold://半粗体 600
  33. if let aName = fontNames.first(where: { $0.lowercased().hasSuffix("-semibold") || $0.lowercased().hasSuffix("_semibold") }) {
  34. finalFontName = aName
  35. }
  36. case .heavy: //粗黑体 800
  37. if let aName = fontNames.first(where: { $0.lowercased().hasSuffix("-heavy") || $0.lowercased().hasSuffix("_heavy") }) {
  38. finalFontName = aName
  39. }
  40. case .black: // 黑体 900
  41. if let aName = fontNames.first(where: { $0.lowercased().hasSuffix("-black") || $0.lowercased().hasSuffix("_black") }) {
  42. finalFontName = aName
  43. }
  44. default:
  45. break
  46. }
  47. return UIFont(name: finalFontName, size: size)!
  48. }
  49. }
  50. extension UIFont {
  51. /// 返回该字体下,对应字符的宽度
  52. /// - Parameter word: 字符
  53. /// - Returns: 宽度
  54. public func widthForWord(_ word: String) -> CGFloat {
  55. let sizeWidth = (word as NSString).size(withAttributes: [.font: self]).width
  56. return sizeWidth//.rounded(.up)
  57. }
  58. }