話不多說 直接貼代碼
寫一個UIFont的分類方法即可:
#import "UIFont+FontFit.h"
//按照6s大小來適配
#define p [UIScreen mainScreen].bounds.size.width / 375.0
@implementation UIFont (FontFit)
+ (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 {
if (p < 1) {//5s
fontSize = fontSize - 2;
}
else if (p==1) {//6s
//fontSize = fontSize
} else if (p>1) {//6p
fontSize = fontSize + 2;
}
UIFont *newFont = nil;
newFont = [UIFont adjustFont:fontSize];
return newFont;
}
//此方法只適應於使用了+ (UIFont *)systemFontOfSize:(CGFloat)fontSize 方法