gpt4 book ai didi

ios - Objective-C 默认启用自动收缩

转载 作者:行者123 更新时间:2023-11-29 01:31:43 25 4
gpt4 key购买 nike

是否有可能为 UILabelUIButton 默认启用自动收缩?

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

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

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

最佳答案

尽管我强烈反对(如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

关于ios - Objective-C 默认启用自动收缩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33392424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com