我正在创建一个 iOS 应用程序,其中不同的语言必须使用不同的字体。
我尝试通过在应用程序中和运行时的任何位置使用
systemFont
来实现此目的,并根据语言更改 systemFont
所指的内容。
以下是用于 swizzle
UIFont
- 的类方法的代码
extension UIFont {
static let setSystemFont: Void = {
let m1 = class_getClassMethod(UIFont.self, #selector(systemFont(ofSize:)))!
let m2 = class_getClassMethod(UIFont.self, #selector(customFont(ofSize:)))!
method_exchangeImplementations(m1, m2)
let m3 = class_getClassMethod(UIFont.self, #selector(preferredFont(forTextStyle:)))!
let m4 = class_getClassMethod(UIFont.self, #selector(customFont(forTextStyle:)))!
method_exchangeImplementations(m3, m4)
let m5 = class_getClassMethod(UIFont.self, #selector(boldSystemFont(ofSize:)))!
let m6 = class_getClassMethod(UIFont.self, #selector(boldCustomFont(ofSize:)))!
method_exchangeImplementations(m5, m6)
let m7 = class_getClassMethod(UIFont.self, #selector(italicSystemFont(ofSize:)))!
let m8 = class_getClassMethod(UIFont.self, #selector(italicCustomFont(ofSize:)))!
method_exchangeImplementations(m7, m8)
let m9 = class_getClassMethod(UIFont.self, #selector(systemFont(ofSize:weight:)))!
let m10 = class_getClassMethod(UIFont.self, #selector(customFont(ofSize:weight:)))!
method_exchangeImplementations(m9, m10)
let m11 = class_getClassMethod(UIFont.self, #selector(preferredFont(forTextStyle:compatibleWith:)))!
let m12 = class_getClassMethod(UIFont.self, #selector(customFont(forTextStyle:compatibleWith:)))!
method_exchangeImplementations(m11, m12)
}()
}
private extension UIFont {
@objc
class func customFont(ofSize fontSize: CGFloat) -> UIFont {
UIFont(name: "Chalkduster", size: fontSize)!
}
@objc
class func customFont(forTextStyle style: UIFont.TextStyle) -> UIFont {
UIFont(name: "Chalkduster", size: 15)!
}
@objc
class func boldCustomFont(ofSize fontSize: CGFloat) -> UIFont {
UIFont(name: "Chalkduster", size: fontSize)!
}
@objc
class func italicCustomFont(ofSize fontSize: CGFloat) -> UIFont {
UIFont(name: "Chalkduster", size: fontSize)!
}
@objc
class func customFont(ofSize fontSize: CGFloat, weight: UIFont.Weight) -> UIFont {
UIFont(name: "Chalkduster", size: fontSize)!
}
@objc
class func customFont(forTextStyle style: UIFont.TextStyle, compatibleWith traitCollection: UITraitCollection) -> UIFont {
UIFont(name: "Chalkduster", size: 15)!
}
}
注意 - 使用
Chalkduster
是为了方便观察字体变化。
在
applicationDidFinishLaunching(_:)
中,调用了以下代码
UIFont.setSystemFont
当应用程序运行时,我观察到对于任何以编程方式创建的视图,
systemFont
都会更改并使用Chalkduster
字体。
但是,对于从 xib 文件实例化的任何视图,系统字体不会更改。
谁能指出如何更改 xib 文件中使用的系统字体而不更改 xib 文件中的字体?
这也是一个困扰我的问题...我无法更改xib