一個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([selfclass], @selector(initWithCoder:));
Method myImp = class_getInstanceMethod([selfclass], @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 = [UIFontsystemFontOfSize:fontSize * SizeScale];
}
}
return self;
}
@end
@implementation UILabel (myFont)
+ (void)load{
Method imp = class_getInstanceMethod([selfclass], @selector(initWithCoder:));
Method myImp = class_getInstanceMethod([selfclass], @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 = [UIFontsystemFontOfSize:fontSize * SizeScale];
}
}
return self;
}
@end
@implementation UITextField (myFont)
+ (void)load{
Method imp = class_getInstanceMethod([selfclass], @selector(initWithCoder:));
Method myImp = class_getInstanceMethod([selfclass], @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 = [UIFontsystemFontOfSize:fontSize * SizeScale];
}
}
return self;
}
@end
@implementation UITextView (myFont)
+ (void)load{
Method imp = class_getInstanceMethod([selfclass], @selector(initWithCoder:));
Method myImp = class_getInstanceMethod([selfclass], @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 = [UIFontsystemFontOfSize:fontSize * SizeScale];
}
}
return self;
}
@end