一、需求背景介紹
最近在梳理項目是發現,針對xib創建的控件字體大小使用了runtime替換initWithCoder來實現了統一的處理,而代碼創建的控件都使用了手動處理。這對于后期需求變動開發維護造成很大的工作量。我就考慮如何實現統一的處理?
1.1使用runtime替換UILabel初始化方法
采用runtime機制替換掉UILabel的初始化方法,在其中對label的字體進行默認設置。因為Label可以從initWithFrame、init、new和nib文件4個來源初始化,所以我們需要將這幾個初始化的方法都替換掉。這里我只放出替換一個的方法,其他方法替換自行補全
#import "UILabel+myFont.h"
#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(init));
Method myImp = class_getInstanceMethod([self class], @selector(myInit));
BOOL addMethod = class_addMethod([self class], @selector(init), method_getImplementation(myImp), method_getTypeEncoding(myImp));
if (addMethod) {
class_replaceMethod([self class],
@selector(init),
method_getImplementation(imp),
method_getTypeEncoding(imp));
} else {
method_exchangeImplementations(imp, myImp);
}
}
- (id)myInit{
[self myInit];
if (self) {
CGFloat fontSize = self.font.pointSize;
CGFloat? myFont = SizeScale;
if (SizeScale >1) {
myFont = SizeScale* 0.9;
}
self.font = [UIFont systemFontOfSize:fontSize*myFont];
}
return self;
}
@end
這種方式需要針對不同的控件分別來實現,在后續修改的時候需要修改不同的實現,還是需要處理多個category,這里就考慮不針對個別控件來處理字體大小,而是統一到一個文件來處理所有控件的字體大小。
1.2使用runtime替換UIFont初始化方法
所以控件的字體設置都需要調用uifont的初始化方法,考慮到所有的字體大小設置無非通過如下幾個官方提供的方法。
+ (UIFont *)systemFontOfSize:(CGFloat)fontSize;
+ (UIFont *)boldSystemFontOfSize:(CGFloat)fontSize;
+ (UIFont *)italicSystemFontOfSize:(CGFloat)fontSize;
// Weights used here are analogous to those used with UIFontDescriptor's UIFontWeightTrait.
// See the UIFontWeight... constants in UIFontDescriptor.h for suggested values.
// The caveat above about the use of ...systemFont... methods applies to these methods too.
+ (UIFont *)systemFontOfSize:(CGFloat)fontSize weight:(CGFloat)weight NS_AVAILABLE_IOS(8_2);
所以就給了我們替換這些方法來實現的可能。(我只展示了替換其中一個方法,其他的自行添加)代碼如下:
#define SizeScale ((kScreenHeight > 568) ? kScreenHeight/568 : 1)
#import@implementation NSObject (Extension)
+ (void)originalClassSelector:(SEL)originalSelector withSwizzledClassSelector:(SEL)swizzledSelector{
Method originalMethod = class_getClassMethod(self, originalSelector);
Method swizzledMethod = class_getClassMethod(self, swizzledSelector);
method_exchangeImplementations(originalMethod, swizzledMethod);
}
@end
@implementation UIFont (KCFont)
+ (void)load{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
[self originalClassSelector:@selector(systemFontOfSize:) withSwizzledClassSelector:@selector(kc_systemFontOfSize:)];
});
}
+ (UIFont *)kc_systemFontOfSize:(CGFloat)fontSize{
return [self kc_systemFontOfSize:fontSize*(SizeScale>1?SizeScale*0.9:SizeScale)];
}
二、寫在最后
通過實現UIlabel等控件的category的好處是可以根據不同的tag來處理不同的控件字體需求,缺點是需要針對不同控件都需要處理。通過實現UIFont的category可以做到所有的控件字體,但是對于特殊化需求支持有所欠缺。
相關鏈接: