在整个应用程序中动态更改字体系列

Change font family dynamically throughout app

我正在从事一个多目标项目,该项目由两个应用程序组成,每个应用程序都有自己的品牌。

我已经区分了应用程序名称、应用程序图标和应用程序的品牌颜色,但现在我需要在从 API 获取品牌详细信息后动态切换应用程序的字体系列。

我要解决的问题是保持相同的字体大小但使用不同的字体系列。

我尝试寻找一种方法使不同字体系列的字体大小保持相同,但没有成功,如果您有任何解决此特殊情况的建议,请告诉我。

使用 NUI 在几分钟内更新整个应用程序的视觉外观。您只需在两个不同的文件中定义 Theme1.nssTheme2.nss 等主题,然后 AppDelegate 的 application didFinishLaunchingWithOptions 方法您只需告诉 NUI 框架将这些主题相应地加载到目标

if Target1

[NUISettings initWithStylesheet:@"Theme1"];    

#elif Target2

[NUISettings initWithStylesheet:@"Theme2"];

#endif

我找到了一种通过方法调配来解决这个问题的方法。以下是解决此问题的步骤:

  • 第 1 步:创建 UIFont 的扩展和以下代码以覆盖字体名称和系列运行时。

代码示例:

  var appFontName = "ArialMT"
  var appFontBoldName = "Arial-BoldMT"

 extension UIFontDescriptor.AttributeName {
   static let nsctFontUIUsage = UIFontDescriptor.AttributeName(rawValue: "NSCTFontUIUsageAttribute")
 } 

extension UIFont {

@objc class func mySystemFont(ofSize size: CGFloat) -> UIFont {
    return UIFont(name: appFontName, size: size)!
}

@objc class func myBoldSystemFont(ofSize size: CGFloat) -> UIFont {
    return UIFont(name: appFontBoldName, size: size)!
}

@objc convenience init(myCoder aDecoder: NSCoder) {

    guard let fontDescriptor = aDecoder.decodeObject(forKey: "UIFontDescriptor") as? UIFontDescriptor else  {
        self.init(myCoder: aDecoder)
        return
    }
    let face = fontDescriptor.object(forKey: UIFontDescriptor.AttributeName.face) as? String ?? "Regular"
    var fontName = appFontName

    switch face {
    case "Regular":
        fontName = appFontName
    case "Bold":
        fontName = appFontBoldName
    default:
        fontName = appFontName
    }
    self.init(name: fontName, size: fontDescriptor.pointSize)!
}

class func overrideInitialize() {
    if self == UIFont.self {
        let systemFontMethod = class_getClassMethod(self, #selector(systemFont(ofSize:)))
        let mySystemFontMethod = class_getClassMethod(self, #selector(mySystemFont(ofSize:)))
        method_exchangeImplementations(systemFontMethod!, mySystemFontMethod!)

        let boldSystemFontMethod = class_getClassMethod(self, #selector(boldSystemFont(ofSize:)))
        let myBoldSystemFontMethod = class_getClassMethod(self, #selector(myBoldSystemFont(ofSize:)))
        method_exchangeImplementations(boldSystemFontMethod!, myBoldSystemFontMethod!)

        let initCoderMethod = class_getInstanceMethod(self, #selector(UIFontDescriptor.init(coder:)))
        let myInitCoderMethod = class_getInstanceMethod(self, #selector(UIFont.init(myCoder:)))
        method_exchangeImplementations(initCoderMethod!, myInitCoderMethod!)
    }
  }
}
  • 第二步:(用法)并调用overrideInitialize方法。

    UIFont.overrideInitialize()
    

它通过更改整个应用程序的字体系列来保留字体大小。 :)