默认情况下是否有可能为UILabel
和UIButton
启用自动缩小功能?
基本上,我需要让他们运行这段代码:
self.adjustsFontSizeToFitWidth = YES;
self.minimumScaleFactor = 0.5;
即使它们是从.xib
文件或代码初始化的,也无需使用自定义MyLabel
替换。
答案 0 :(得分:1)
虽然我强烈建议反对(如the question comments中所述),但这是使用method swizzling
和category
实现此目的的方法:
<强>的UILabel + SwizzledInitializer.h 强>:
//
// UILabel+SwizzledInitializer.h
//
#import <UIKit/UIKit.h>
@interface UILabel (SwizzledInitializer)
@end
<强>的UILabel + SwizzledInitializer.m 强>:
//
// UILabel+SwizzledInitializer.m
//
#import "UILabel+SwizzledInitializer.h"
#import <objc/runtime.h>
@implementation UILabel (SwizzledInitializer)
+ (void)load
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [self class];
SEL originalSelector = @selector(initWithFrame:);
SEL swizzledSelector = @selector(initWithFrame_swizzledForAutoShrink:);
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
BOOL didAddMethod = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
});
}
- (instancetype)initWithFrame_swizzledForAutoShrink:(CGRect)frame;
{
self = [self initWithFrame_swizzledForAutoShrink:frame];
if (self) {
self.adjustsFontSizeToFitWidth = YES;
self.minimumScaleFactor = 0.5;
}
return self;
}
@end