iOS -不同模拟器字体适配

1.先建立一个UILabel的分类

导入#import <objc/runtime.h>头文件

2.在.m文件中写入如下代码

//不同设备的屏幕比例(当然倍数可以自己控制)

#define IPHONE_HEIGHT  [UIScreen mainScreen].bounds.size.height

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

@implementation UILabel(myFont)

+ (void)load{

Method imp = class_getInstanceMethod([self class], @selector(initWithCoder:));

Method myImp = class_getInstanceMethod([self class], @selector(myInitWithCoder:));

method_exchangeImplementations(imp, myImp);

Method cmp = class_getInstanceMethod([self class], @selector(initWithFrame:));

Method myCmp = class_getInstanceMethod([self class], @selector(myInitWithFrame:));

method_exchangeImplementations(cmp, myCmp);

}

- (id)myInitWithCoder:(NSCoder*)aDecode{

[self myInitWithCoder:aDecode];

if (self) {

//部分不像改变字体的 把tag值设置成333跳过

if(self.tag != 333){

CGFloat fontSize = self.font.pointSize;

self.font = [UIFont systemFontOfSize:fontSize * SizeScale];

NSLog(@" label的大小 == %f", self.font.pointSize);

}

}

return self;

}

- (id)myInitWithFrame:(CGRect)frame{

[self myInitWithFrame:frame];

if(self){

CGFloat fontSize = self.font.pointSize;

self.font = [UIFont systemFontOfSize:fontSize * SizeScale];

NSLog(@" label的大小 == %f", self.font.pointSize);

}

return self;

}

@end

3.在调用文件中导入分类

#import "ViewController.h"

#import "UIButton+myFont.h"

@interface ViewController ()

/*注释*/

@property (nonatomic,strong)UILabel *label;

@end

@implementation ViewController

- (void)viewDidLoad {

[super viewDidLoad];

[self.view addSubview:self.label];

// Do any additional setup after loading the view, typically from a nib.

}

- (void)viewWillAppear:(BOOL)animated

{

NSLog(@"%@",self.label.font);

}

- (void)didReceiveMemoryWarning {

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

- (UILabel *)label{

if (!_label) {

_label = [[UILabel alloc]initWithFrame:CGRectMake(50, 100, 100, 30)];

//        _label.font = [UIFont systemFontOfSize:17];

_label.tag = 32;

_label.text = @"这是测试文字";

}

return _label;

}

@end

上一篇:Linux学习---自定义数据类型


下一篇:混沌数学之Baker模型