iOS开发小技巧 - runtime适配字体

时间:2022-06-14 00:47:24

iOS开发小技巧 - runtime适配字体

版权声明:本文为博主原创文章,未经博主允许不得转载,有问题可联系博主Email: liuyongjiesail@icloud.com

一个iOS开发项目无外乎就是纯代码布局、xib或SB布局。那么如何实现两个方式的字体大小适配呢?

字体大小适配------纯代码

定义一个宏定义如下:

#define SizeScale (SCREEN_WIDTH != 414 ? 1 : 1.2)

#define kFont(value) [UIFont systemFontOfSize:value * SizeScale]

宏中的1.2是在plus下的大小放大比例,可以根据自己的实际情况来调整。

纯代码中设置字体大小通过使用这个宏来实现整体适配

字体大小适配------xib或SB

字体大小适配无外乎就是设置UIButton、UILabel、UITextView、UITextField的字体大小

通过创建这几个的类目来实现(Runtime方式的黑魔法method swizzling)

废话不多说,直接上代码:

.h

#import <UIKit/UIKit.h>
#import <objc/runtime.h> /**
* button
*/
@interface UIButton (MyFont) @end /**
* Label
*/
@interface UILabel (myFont) @end /**
* TextField
*/ @interface UITextField (myFont) @end /**
* TextView
*/
@interface UITextView (myFont) @end

.m

#import "UIButton+MyFont.h"

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

@implementation UIButton (MyFont)

+ (void)load{
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) { //部分不像改变字体的 把tag值设置成333跳过
if(self.titleLabel.tag != 333){
CGFloat fontSize = self.titleLabel.font.pointSize;
self.titleLabel.font = [UIFont systemFontOfSize:fontSize * SizeScale];
}
}
return self;
} @end @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);
} - (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];
}
}
return self;
} @end @implementation UITextField (myFont) + (void)load{
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) {
//部分不像改变字体的 把tag值设置成333跳过
if(self.tag != 333){
CGFloat fontSize = self.font.pointSize;
self.font = [UIFont systemFontOfSize:fontSize * SizeScale];
}
}
return self;
} @end @implementation UITextView (myFont) + (void)load{
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) {
//部分不像改变字体的 把tag值设置成333跳过
if(self.tag != 333){
CGFloat fontSize = self.font.pointSize;
self.font = [UIFont systemFontOfSize:fontSize * SizeScale];
}
}
return self;
} @end