iOS字体大小适配

在iOS中,有些公司对字体也有适配要求,可以最大程度上利用Objective-C的动态语言特性,去适配。

class_getInstanceMethod得到类的实例方法
class_getClassMethod得到类的类方法

1. 首先需要创建一个UIFont的分类
2. 自己UI设计原型图的手机尺寸宽度
#define MyUIScreen  375 // UI设计原型图的手机尺寸宽度(6), 6p的--414
UIFont+runtime.h

#import 

@interface UIFont (runtime)

@end
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:));
    // 然后交换类方法,交换两个方法的IMP指针,(IMP代表了方法的具体的实现)
    method_exchangeImplementations(newMethod, method);
}

+ (UIFont *)adjustFont:(CGFloat)fontSize {
    UIFont *newFont = nil;
    newFont = [UIFont adjustFont:fontSize * [UIScreen mainScreen].bounds.size.width/MyUIScreen];
    return newFont;
}
@end
Controller类中正常调用就行了:
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 150, [UIScreen mainScreen].bounds.size.width, 60)];
label.text = @"适配字体大小";
label.backgroundColor = [UIColor yellowColor];
label.font = [UIFont systemFontOfSize:16];
[self.view addSubview:label];

注意:
load方法只会走一次,利用runtime的method进行方法的替换
替换的方法里面(把系统的方法替换成我们自己写的方法),这里要记住写自己的方法,不然会死循环
之后凡是用到systemFontOfSize方法的地方,都会被替换成我们自己的方法,即可改字体大小了
注意:此方法只能替换 纯代码 写的控件字号,如果你用xib创建的控件且在xib里面设置的字号,那么替换不了!你需要在xib的
awakeFromNib方法里面手动设置下控件字体

------整理

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