在iOS中,有些公司對(duì)字體也有適配要求,可以最大程度上利用Objective-C的動(dòng)態(tài)語言特性,去適配。
class_getInstanceMethod得到類的實(shí)例方法
class_getClassMethod得到類的類方法
1. 首先需要?jiǎng)?chuàng)建一個(gè)UIFont的分類
2. 自己UI設(shè)計(jì)原型圖的手機(jī)尺寸寬度
#define MyUIScreen 375 // UI設(shè)計(jì)原型圖的手機(jī)尺寸寬度(6), 6p的--414
UIFont+runtime.h
#import <UIKit/UIKit.h>
@interface UIFont (runtime)
@end
UIFont+runtime.m
#import "UIFont+runtime.h"
#import <objc/runtime.h>
@implementation UIFont (runtime)
+ (void)load {
// 獲取替換后的類方法
Method newMethod = class_getClassMethod([self class], @selector(adjustFont:));
// 獲取替換前的類方法
Method method = class_getClassMethod([self class], @selector(systemFontOfSize:));
// 然后交換類方法,交換兩個(gè)方法的IMP指針,(IMP代表了方法的具體的實(shí)現(xiàn))
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類中正常調(diào)用就行了:
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方法只會(huì)走一次,利用runtime的method進(jìn)行方法的替換
替換的方法里面(把系統(tǒng)的方法替換成我們自己寫的方法),這里要記住寫自己的方法,不然會(huì)死循環(huán)
之后凡是用到systemFontOfSize方法的地方,都會(huì)被替換成我們自己的方法,即可改字體大小了
注意:此方法只能替換 純代碼 寫的控件字號(hào),如果你用xib創(chuàng)建的控件且在xib里面設(shè)置的字號(hào),那么替換不了!你需要在xib的
awakeFromNib方法里面手動(dòng)設(shè)置下控件字體
------整理