iosiOS Swift && Objective-Cios实用开发技巧

关于字体适配的问题

2017-07-03  本文已影响37人  明月钓无痕

之前没有做过字体适配.这次突然提 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如何使用自己添加的字体库

上一篇 下一篇

猜你喜欢

热点阅读