默认情况下在Objective-C中启用自动收缩

时间:2015-10-28 13:31:51

标签: ios objective-c uibutton uilabel

默认情况下是否有可能为UILabelUIButton启用自动缩小功能?

基本上,我需要让他们运行这段代码:

self.adjustsFontSizeToFitWidth = YES;
self.minimumScaleFactor = 0.5;

即使它们是从.xib文件或代码初始化的,也无需使用自定义MyLabel替换。

1 个答案:

答案 0 :(得分:1)

虽然我强烈建议反对(如the question comments中所述),但这是使用method swizzlingcategory实现此目的的方法:

<强>的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