创建个UIButton类目, 名字叫AutoFontSize;
.h文件代码
#import <UIKit/UIKit.h>
#import <objc/runtime.h>
@interface UIButton (AutoFontSize)
@end
@interface UILabel (AutoFontSize)
@end
@interface UITextField (AutoFontSize)
@end
@interface UITextView (AutoFontSize)
@end
.m文件代码
#import "UIButton+AutoFontSize.h"
@implementation UIButton (AutoFontSize)
+ (void)load{
Method imp =class_getInstanceMethod([selfclass], @selector(initWithCoder:));
Method myImp =class_getInstanceMethod([selfclass], @selector(myInitWithCoder:));
method_exchangeImplementations(imp, myImp);
}
- (id)myInitWithCoder:(NSCoder*)aDecode{
[selfmyInitWithCoder:aDecode];
if (self) {
//部分不像改变字体的把tag值设置成333跳过
if(self.titleLabel.tag != 333){
CGFloat fontSize =self.titleLabel.font.pointSize;
self.titleLabel.font = [UIFontsystemFontOfSize:fontSize *OffWidth];
}
}
returnself;
}
@end
@implementation UILabel (AutoFontSize)
+ (void)load{
Method imp =class_getInstanceMethod([selfclass], @selector(initWithCoder:));
Method myImp =class_getInstanceMethod([selfclass], @selector(myInitWithCoder:));
method_exchangeImplementations(imp, myImp);
}
- (id)myInitWithCoder:(NSCoder*)aDecode{
[selfmyInitWithCoder:aDecode];
if (self) {
NSLog(@"%@",self.font);
//部分不像改变字体的把tag值设置成333跳过
if(self.tag != 333){
CGFloat fontSize =self.font.pointSize;
self.font = [UIFontsystemFontOfSize:fontSize *OffWidth - 1];
}
}
returnself;
}
@end
@implementation UITextField (AutoFontSize)
+ (void)load{
Method imp =class_getInstanceMethod([selfclass], @selector(initWithCoder:));
Method myImp =class_getInstanceMethod([selfclass], @selector(myInitWithCoder:));
method_exchangeImplementations(imp, myImp);
}
- (id)myInitWithCoder:(NSCoder*)aDecode{
[selfmyInitWithCoder:aDecode];
if (self) {
//部分不像改变字体的把tag值设置成333跳过
if(self.tag != 333){
CGFloat fontSize =self.font.pointSize;
self.font = [UIFontsystemFontOfSize:fontSize *OffWidth];
}
}
returnself;
}
@end
@implementation UITextView (AutoFontSize)
+ (void)load{
Method imp =class_getInstanceMethod([selfclass], @selector(initWithCoder:));
Method myImp =class_getInstanceMethod([selfclass], @selector(myInitWithCoder:));
method_exchangeImplementations(imp, myImp);
}
- (id)myInitWithCoder:(NSCoder*)aDecode{
[selfmyInitWithCoder:aDecode];
if (self) {
//部分不像改变字体的把tag值设置成333跳过
if(self.tag != 333){
CGFloat fontSize =self.font.pointSize;
self.font = [UIFontsystemFontOfSize:fontSize *OffWidth];
}
}
returnself;
}
@end
在pch文件里import
#import "UIButton+AutoFontSize.h"
完事
原理:
中二点的叫rutime黑魔法 :method_exchangeImplementations 交换系统方法, 当系统需要调用initWithCoder方法时使其不去调用initWithCoder而是去调用自己定义的- myInitWithCoder方法, 在方法里把字体大小乘上屏幕比例