iphone - UILabel 类别和 setFont : crash

标签 iphone ios uilabel categories

我创建了 UILabel 类别,它会在字体属性更改时做额外的工作。

我选择了类别而不是分类,所以我不必更改所有 XIB 文件中所有标签的类别。我只是将这个类别声明添加到前缀标题中,类别在整个项目范围内都是可见的。

执行文件:

//
//  UILabel+XIBCustomFonts.m


#import "UILabel+XIBCustomFonts.h"

@implementation UILabel (XIBCustomFonts)
BOOL comes_from_nib = NO;


-(id)initWithCoder:(NSCoder *)aDecoder_{

    self = [super initWithCoder:aDecoder_];

    if (self) {
        comes_from_nib = YES;

    }
    return self;
}

-(void)setFont:(UIFont *)font_{

    [super setFont:font_];
    NSLog(@"Setting from for label from XIB for name:%@ size: %.1f - do font theme replacement if needed", self.font.fontName, self.font.pointSize);

}
@end

令人惊讶的是以下日志的崩溃:

-[UIButtonLabel setFont:]: unrecognized selector sent to instance 0x9ad1b70
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIButtonLabel setFont:]: unrecognized selector sent to instance 0x9ad1b70'

UIButtonLabel 是从哪里来的?

即使我在 setFont: setter:

中进行额外的类检查也会发生这种情况
if ([self class] != [UILabel class] || !comes_from_nib) {

        [super setFont:font_];
        return;

    }

有没有什么方法可以在不进行子类化的情况下覆盖 UILabel 中的 setFont: setter?

最佳答案

您不能在类别中调用 super 方法!绝不! 当您使用类别来扩充类的功能时,这是不可能的,您不是在扩展类,您实际上是在完全覆盖现有方法,您完全失去了原始方法。这就是出现错误的原因。

关于iphone - UILabel 类别和 setFont : crash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12474868/

相关文章:

ios - 如何在 Expo 项目中获取 iOS 的 'facebookScheme'?

ios - 其他 View 上的 UILabel 换行符

iphone - iOS Google Plus 整合与分享

iphone - 无法理解 iPhone View 布局

ios - 使用 AVCaptureSession 录制视频

iphone - 在后台模式下播放音频不起作用

ios - 在方向改变时改变整个用户界面

ios - 如何从我的 iPhone 应用程序导入/导出我的 Realm 数据库

iphone - 如何检查我的 UILabel 值是否大于 0?

ios - 在 UIView 中显示 UILabel 的属性文本