关于字体适配的问题

之前没有做过字体适配.这次突然提 bug 说是,字体在5上面看着大.突然觉得有点蒙.😁怎么办那么多字体....
言归正传,在这种情况下对于字体的适配,使用 runtime 还是比较简单的. runtime 终于有用武之地了.
如下添加一个UIFont+JZAuto分类. 使用

**************************.h 文件*******************************
#import <UIKit/UIKit.h>
#import <objc/runtime.h>

@interface UIFont (JZAuto)

+ (UIFont *)autoFontWithName:(NSString *)fontName size:(CGFloat)fontSize;

+ (UIFont *)autoSystemFontOfSize: (CGFloat)fontSize;

**************************.m 文件*******************************

#import "UIFont+JZAuto.h"
#import <objc/runtime.h>

@implementation UIFont (JZAuto)
// 使用 runtime 进行方法交换
+ (void)load {
    
    Method newMethod = class_getClassMethod([self class], @selector(autoFontWithName:size:));
    
    Method oldMethod = class_getClassMethod([self class], @selector(fontWithName:size:));
    
    method_exchangeImplementations(newMethod, oldMethod);
    
    newMethod = class_getClassMethod([self class], @selector(autoSystemFontOfSize:));
    
     oldMethod = class_getClassMethod([self class], @selector(systemFontOfSize:));
    
    method_exchangeImplementations(newMethod, oldMethod);
}

+ (UIFont *)autoFontWithName:(NSString *)fontName size:(CGFloat)fontSize {
    // 根据屏幕的宽度 进行字体的大小的适配.如果有设计要求,可替换成要求的字体大小
    return [UIFont autoFontWithName:fontName size:fontSize * ([UIScreen mainScreen].bounds.size.width / 375.0)];
}

+ (UIFont *)autoSystemFontOfSize: (CGFloat)fontSize {
    
    return [UIFont autoSystemFontOfSize:fontSize * ([UIScreen mainScreen].bounds.size.width / 375.0)];
}
@end

如果使用 swift 的话,我们会发现重写 load() 方法会报错.在initialize()里面是没有问题的.

override open static func initialize() {
// 交换方法
}

项目中使用到了第三方字体,iphone的字体库中没有,可参考之前写过的:iOS如何使用自己添加的字体库

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,267评论 4 61
  • 在太平洋的一个小岛上生活着土人,他们不愿意被外人打扰,一天,一个探险家到了岛上,被土人抓住,土人的祭司告诉他,你临...
    莫西西子阅读 367评论 0 0
  • 水之能量,任谁不可小觑。山洪来时,裹挟摧毁一切的力量;冰冻之际,瞬间凝固一切的能量;大海风浪袭来,吞噬席卷一切的存...
    韧性十足的牛皮糖阅读 687评论 0 0