iOS

UIFont字体适配

2018-03-13  本文已影响1人  飞鱼ll

代码适配

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

#define MyUIScreen  375 // UI设计原型图的手机尺寸宽度(6s), 6p的--414

@implementation UIFont (DXFont)

+ (void)load{
    
    //获取替换后的类方法
    Method newMethod = class_getClassMethod([self class], @selector(adjustFont:));
    //获取替换前的类方法
    Method method = class_getClassMethod([self class], @selector(systemFontOfSize:));
    //然后交换类方法
    method_exchangeImplementations(newMethod, method);
    
}

// 以6s未基准(因为一般UI设计是以6s尺寸为基准设计的)的字体。在5s和6P上会根据屏幕尺寸,字体大小会相应的扩大和缩小
+ (UIFont *)adjustFont:(CGFloat)fontSize {
    UIFont *newFont = nil;
    newFont = [UIFont adjustFont:fontSize * [UIScreen mainScreen].bounds.size.width/MyUIScreen];
    return newFont;
}

@end

xib适配

#import "UILabel+DXFont.h"
#import <objc/runtime.h>

@implementation UILabel (DXFont)

+ (void)load{
    //利用running time运行池的方法在程序启动的时候把两个方法替换 适用Xib建立的label
    Method imp = class_getInstanceMethod([self class], @selector(initWithCoder:));
    Method myImp = class_getInstanceMethod([self class], @selector(myInitWithCoder:));
    method_exchangeImplementations(imp, myImp);  //交换方法
}

- (id)myInitWithCoder:(NSCoder*)aDecode{
    [self myInitWithCoder:aDecode];
    if (self) {
        CGFloat fontSize = self.font.pointSize;
        self.font = [UIFont systemFontOfSize:fontSize];
    }
    return self;
}

@end
#import "UIButton+DXFont.h"
#import <objc/runtime.h>

@implementation UIButton (DXFont)

+ (void)load{
    
    //利用running time运行池的方法在程序启动的时候把两个方法替换 适用Xib建立的label
    Method imp = class_getInstanceMethod([self class], @selector(initWithCoder:));
    Method myImp = class_getInstanceMethod([self class], @selector(myInitWithCoder:));
    method_exchangeImplementations(imp, myImp);  //交换方法
}

- (id)myInitWithCoder:(NSCoder*)aDecode{
    [self myInitWithCoder:aDecode];
    if (self) {
        CGFloat fontSize = self.titleLabel.font.pointSize;
        self.titleLabel.font = [UIFont systemFontOfSize:fontSize];
    }
    return self;
}

@end

参考文章:
https://www.jianshu.com/p/8b8731ed84f8
https://www.jianshu.com/p/0541caf7cecb

上一篇下一篇

猜你喜欢

热点阅读