Swift 4.0
这将帮助您为所有UILabel、UIButton等设置自定义字体。只需创建一个扩展并替换为此代码即可:
var appFontName = "Gudea"
var appFontBoldName = "Gudea"
var appFontItalicName = "Gudea"
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 class func myItalicSystemFont(ofSize size: CGFloat) -> UIFont {
return UIFont(name: appFontItalicName, size: size)!
}
@objc convenience init(myCoder aDecoder: NSCoder) {
if let fontDescriptor = aDecoder.decodeObject(forKey: "UIFontDescriptor") as? UIFontDescriptor {
if let fontAttribute = fontDescriptor.fontAttributes[UIFontDescriptor.AttributeName(rawValue: "NSCTFontUIUsageAttribute")] as? String {
var fontName = ""
switch fontAttribute {
case "CTFontRegularUsage":
fontName = appFontName
case "CTFontEmphasizedUsage", "CTFontBoldUsage":
fontName = appFontBoldName
case "CTFontObliqueUsage":
fontName = appFontItalicName
default:
fontName = appFontName
}
self.init(name: fontName, size: fontDescriptor.pointSize)!
}
else {
self.init(myCoder: aDecoder)
}
}
else {
self.init(myCoder: aDecoder)
}
}
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 italicSystemFontMethod = class_getClassMethod(self, #selector(italicSystemFont(ofSize:)))
let myItalicSystemFontMethod = class_getClassMethod(self, #selector(myItalicSystemFont(ofSize:)))
method_exchangeImplementations(italicSystemFontMethod!, myItalicSystemFontMethod!)
let initCoderMethod = class_getInstanceMethod(self, #selector(UIFontDescriptor.init(coder:)))
let myInitCoderMethod = class_getInstanceMethod(self, #selector(UIFont.init(myCoder:)))
method_exchangeImplementations(initCoderMethod!, myInitCoderMethod!)
}
}
}
更新:Swift3.2
请将此行替换为:
if let fontAttribute = fontDescriptor.fontAttributes[UIFontDescriptor.AttributeName(rawValue: "NSCTFontUIUsageAttribute")] as? String {
使用:
if let fontAttribute = fontDescriptor.fontAttributes["NSCTFontUIUsageAttribute"] as? String {
self
(UILabel) 为空。尝试在稍后的阶段调用它。 - jonaszmclaren