如何使用 UIAppearance 在 View Controller 中正确设置所有标签的字体

How Properly To Set Font for All Labels in View Controller Using UIAppearance

我试图将整个应用程序(或至少由 View Controller 控制的标签)中的标签字体设置为相同,因此,我选择了像推荐的那样创建类别的选项 here or here。为此,我在 UILabel 类别中创建了方法 "setSubstituteFont"。但是,语法

[[UILabel appearance] setSubstituteFont];

如果我将该语句放入我的视图控制器中,总是会出现相同的错误:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSMethodSignature getArgumentTypeAtIndex:]: index (2) out of bounds [0, 1]'

我更喜欢在我的视图控制器中实现该功能,因为我的视图是 .xib,因此,使用 "setNeedsDisplay" 作为 here 的建议不是一个选项。

我还尝试了其他选项,例如:

[[UILabel appearanceWhenContainedIn:[UIViewController class], nil] setSubstituteFont];

[[UILabel appearanceWhenContainedIn:[self class], nil] setSubstituteFont];

[[UILabel appearanceForTraitCollection:self.traitCollection] setSubstituteFont];

因为 "appearanceWhenContainedIn" 根据 the documentation 在 iOS9 中被弃用,但仍然出现相同的错误,应用程序崩溃了。

之间,"setSubstituteFont" 方法看起来像这样:

- (void)setSubstituteFont UI_APPEARANCE_SELECTOR {
    self.font = [UIFont fontWithName:@"GothamRounded-Book" size:54.0];
}

使用的选择器取自the list

试试这个

@interface UILabel (UIAPP)
- (void)setSubstituteFont:(UIFont *)font UI_APPEARANCE_SELECTOR;
@end


@implementation UILabel (UIAPP)
- (void)setSubstituteFont:(UIFont *)font {
    if (font == nil) {
        self.font = [UIFont fontWithName:@"GothamRounded-Book" size:54.0];
    } else {
        self.font = font;
    }
}
@end

即使在 View Controller 中也可以在需要的地方调用:

[[UILabel appearance] setSubstituteFont: nil];