这是 Objective-C 运行时解决方案:
@interface UIFont (CustomSystemFont)
+ (UIFont *)ln_systemFontOfSize:(CGFloat)fontSize;
+ (UIFont *)ln_boldSystemFontOfSize:(CGFloat)fontSize;
+ (UIFont *)ln_italicSystemFontOfSize:(CGFloat)fontSize;
@end
@implementation UIFont (CustomSystemFont)
+ (void)load
{
Method orig = class_getClassMethod([UIFont class], @selector(systemFontOfSize:));
Method swiz = class_getClassMethod([UIFont class], @selector(ln_systemFontOfSize:));
method_exchangeImplementations(orig, swiz);
orig = class_getClassMethod([UIFont class], @selector(boldSystemFontOfSize:));
swiz = class_getClassMethod([UIFont class], @selector(ln_boldSystemFontOfSize:));
method_exchangeImplementations(orig, swiz);
orig = class_getClassMethod([UIFont class], @selector(italicSystemFontOfSize:));
swiz = class_getClassMethod([UIFont class], @selector(ln_italicSystemFontOfSize:));
method_exchangeImplementations(orig, swiz);
}
+ (UIFont *)ln_systemFontOfSize:(CGFloat)fontSize
{
if([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0f)
{
//Call original implementation.
return [self ln_systemFontOfSize:fontSize];
}
return [UIFont fontWithName:@"HelveticaNeue" size:fontSize];
}
+ (UIFont *)ln_boldSystemFontOfSize:(CGFloat)fontSize
{
if([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0f)
{
//Call original implementation.
return [self ln_systemFontOfSize:fontSize];
}
return [UIFont fontWithName:@"HelveticaNeue-Medium" size:fontSize];
}
+ (UIFont *)ln_italicSystemFontOfSize:(CGFloat)fontSize
{
if([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0f)
{
//Call original implementation.
return [self ln_systemFontOfSize:fontSize];
}
return [UIFont fontWithName:@"HelveticaNeue-Italic" size:fontSize];
}
@end
我在这个例子中所做的是将三种系统字体方法替换为我自己的并测试系统版本是否为 7 或更高版本。如果是,我使用原始方法,否则返回我选择的字体(在这种情况下,Helvetica Neue 对于常规和斜体请求具有 UltraLight 粗细,对于粗体请求具有中等粗细)。
这适用于代码中生成的所有内容,包括系统创建的视图。从 Xib 和 Storyboard 文件加载视图时它不起作用,因为字体在 NIB 文件本身中是硬编码的。使用字体选择器选择您需要的字体。