iOS字体适配

随着iPhone机型种类的增加,iOS的小开发仔们各种机型的屏幕适配,字体适配是否困扰着你呢?我们都知道屏幕适配有多种方法:比例适配,xib,第三方marsonry等,但是这些方法只是解决屏幕的适配,但是字体并没有适配。开发过程中我们会发现明明是按照UI给的尺寸去写的字体大小,但是在自己的手机上看起来总显得那么小巧玲珑呢?
下面我介绍两种我使用过的感觉比较好用的字体适配方法:

  • 等比适配法:
假设UI给出了一套6的UI标注图,那么实际的字体大小由下面的kFont根据等比原则来定义
#define kFont(a) [UIFont systemFontOfSize:(a/ 375.0 * kScreenWidth)] //字体大小
  • 全局方法替换:假设是Plus,就在原来的基础上将字体放大两个
#import "UILabel+Adapter.h"
#import <objc/runtime.h>
@implementation UILabel (Adapter)
+ (void)load {
   static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class class = [self class];
        SEL originalSelector = @selector(initWithCoder:);
        SEL swizzledSelector = @selector(adapterInitWithCoder:);
        Method originalMethod = class_getInstanceMethod(class, originalSelector);
        Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
        BOOL didAddMethod = class_addMethod(class,
                                            originalSelector,
                                            method_getImplementation(swizzledMethod),
                                            method_getTypeEncoding(swizzledMethod));
        if (didAddMethod) {
            class_replaceMethod(class,
                                swizzledSelector,
                                method_getImplementation(originalMethod),
                                method_getTypeEncoding(originalMethod));
        } else {
            method_exchangeImplementations(originalMethod, swizzledMethod);
        }
    });
}
- (instancetype)adapterInitWithCoder:(NSCoder *)aDecoder {
    [self adapterInitWithCoder:aDecoder];
    if (self) {
        if (OB_SCREEN_WIDTH == 414) {
            //6P 7P 8P
             self.font = [UIFont fontWithName:self.font.fontName size:self.font.pointSize + 2];
        }
    }
    return self;
}
-(void)awakeFromNib
{
    [super awakeFromNib];
    if (OB_SCREEN_WIDTH == 414) {
        //6P 7P 8P
        self.font = [UIFont fontWithName:self.font.fontName size:self.font.pointSize + 2];
    }
}
@end