参考门前有棵葡萄树
我这里添加一个用代码创建的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
有不足之处请指出
网友评论