runtime字体大小适配

字体大小适配-runtime

在开发过程中, 我选择的模拟器是7P, 当我把模拟器改换成5的时候发现字体大的吓人, 简直就是老年机那种恐怖大的字体, 所以这时候就需要做一下字体的适配了.

之前的愚蠢的做法是在每个有文字内容的地方通过判断屏幕宽度大小来适配字体的大小, 不但麻烦, 而且愚蠢... 所以这次在一个群里(群号:139571656)看到群主Edison的一个demo, 使用runtime的方法来做的适配, 简单方便有效.

实现思想是在程序运行的时候动态修改系统方法systemFontOfSize:, 跟设计图上的字体大小按比例做适配;

  1. 首先需要创建一个UIFont的分类

  2. 自己UI设计原型图的手机尺寸宽度

#define YourUIScreen 414
  1. UIFont+runtime.m文件中
#import "UIFont+runtime.h"
#import 
@implementation UIFont (runtime)

+(void)load{
    //获取替换后的类方法
    Method newMethod = class_getClassMethod([self class], @selector(adjustFont:));
    //获取替换前的类方法
    Method method = class_getClassMethod([self class], @selector(systemFontOfSize:));
    //然后交换类方法
    method_exchangeImplementations(newMethod, method);
}

+(UIFont *)adjustFont:(CGFloat)fontSize{
    UIFont *newFont=nil;
    newFont = [UIFont adjustFont:fontSize * [UIScreen mainScreen].bounds.size.width/YourUIScreen];
    return newFont;
}

@end

你可能感兴趣的:(runtime字体大小适配)