建立個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方法, 在方法裡把字型大小乘上螢幕比例