UILable字体大小自适应屏幕大小

font

参考门前有棵葡萄树

我这里添加一个用代码创建的Lable,然后字体大小同样自适应屏幕大小

原理就是给Lable添加一个类目,利用runtime交换系统和自己定义的方法,在自己的方法中根据系统来设置不同的字体(需要考虑不同创建方式).

  • xib

    • initWithCoder
    • myInitWithCoder
  • 代码

    • initWithFrame
    • myInitWithFrame

具体initWithCoder和initWithFrame的区别,我就不说了;以下是类目的.m文件

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

#define SizeScale ((kScreenHeight > 568) ? kScreenHeight/568 : 1)

@implementation UILabel (Font)

+ (void)load{
    //xib创建
    Method imp = class_getInstanceMethod([self class], @selector(initWithCoder:));
    Method myImp = class_getInstanceMethod([self class], @selector(myInitWithCoder:));
    method_exchangeImplementations(imp, myImp);
    
    //代码initwithframe创建
    Method c = class_getInstanceMethod([self class], @selector(initWithFrame:));
    Method d = class_getInstanceMethod([self class], @selector(myInitWithFrame:));
    method_exchangeImplementations(c, d);
}

#pragma mark - xib创建
- (id)myInitWithCoder:(NSCoder*)aDecode{
    [self myInitWithCoder:aDecode];
    if (self) {
        CGFloat fontSize = self.font.pointSize;
        self.font = [UIFont systemFontOfSize:fontSize*SizeScale];
        NSLog(@"%f",SizeScale);
    }
    return self;
}

#pragma mark - 代码initwithframe创建
- (id)myInitWithFrame:(CGRect )rect {
    [self myInitWithFrame:rect];
    if (self) {
        CGFloat fontSize = self.font.pointSize;
        self.font = [UIFont systemFontOfSize:fontSize*SizeScale];
        NSLog(@"%f",SizeScale);
    }
    return self;
}

@end

有不足之处请指出

完整代码请移步gitbub

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

推荐阅读更多精彩内容