3

我正在创建一个 iOS 应用程序,其中不同的字体必须用于不同的语言。

我试图通过systemFont在应用程序和运行时的任何地方使用来做到这一点,systemFont根据语言更改所指的内容。

以下是用于混合类方法的代码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)!
    }
}

Note-Chalkduster用于方便观察字体变化。

applicationDidFinishLaunching(_:),调用以下代码

UIFont.setSystemFont

当应用程序运行时,我观察到对于任何以编程方式创建的视图,systemFont都会更改并使用Chalkduster字体。

但是,对于从 xib 文件实例化的任何视图,系统字体不会更改。

谁能指出如何在不更改 xib 文件中的字体的情况下更改 xib 文件中使用的系统字体?

4

0 回答 0