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