Search code examples
iosobjective-cuilabeluiappearance

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


I am trying to set the font of labels in the whole app (or at least labels controlled by View Controller) the same, therefore, I chose the option of creating category like it is recommended here or here. For these purposes I created the method "setSubstituteFont" in the UILabel category. However, the syntax

[[UILabel appearance] setSubstituteFont];

gives me always the same error if I put that statement in my View Controller:

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

I prefer to implement that feature in my View Controllers since my Views are .xib, therefore, the recomendations to use "setNeedsDisplay" as here are not an option.

I also tried other options like:

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

or

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

or

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

since "appearanceWhenContainedIn" is deprecated in iOS9 according the documentation but still getting the same error, and the app is crashed.

Between, "setSubstituteFont" method looks like that:

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

The used selector was taken from the list.


Solution

  • Try this

    @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
    

    Call where you need even in View Controller:

    [[UILabel appearance] setSubstituteFont: nil];