Custom Fonts with Storyboard

suggest change

Custom fonts for UI components in a storyboard can be set with User Defined Runtime Attributes and categories.

The advantages are:

  1. Font file: Add the font file (.ttf or .otf) to the application target and add its file name to Info.plist under Fonts provided by application (UIAppFonts). See this documentation of custom fonts.
  2. Define categories: Add a file such as UIKit+IBExtensions and add a category for each UI element (UILabel, UIButton, and so on) that should take a custom font. Each category adds a fontName property. Step 4 sets that property from the storyboard.

UIKit+IBExtensions.h

#import <UIKit/UIKit.h>

//Category extension for UILabel
@interface UILabel (IBExtensions)

@property (nonatomic, copy) NSString *fontName;
@end

// Category extension for UITextField
@interface UITextField (IBExtensions)

@property (nonatomic, copy) NSString *fontName;
@end

// Category extension for UIButton
@interface UIButton (IBExtensions)

@property (nonatomic, copy) NSString *fontName;
@end
  1. Getters and setters: Define the getter and setter for fontName on each category. fontWithName:size: returns nil when fontName is not the font’s PostScript name, and the control’s font then becomes nil. The size is the control’s current point size.

UIKit+IBExtensions.m

#import "UIKit+IBExtensions.h"

@implementation UILabel (IBExtensions)

- (NSString *)fontName {
    return self.font.fontName;
}

- (void)setFontName:(NSString *)fontName {
    self.font = [UIFont fontWithName:fontName size:self.font.pointSize];
}
@end

@implementation UITextField (IBExtensions)

- (NSString *)fontName {
    return self.font.fontName;
}

- (void)setFontName:(NSString *)fontName {
    self.font = [UIFont fontWithName:fontName size:self.font.pointSize];
}
@end

@implementation UIButton (IBExtensions)

- (NSString *)fontName {
    return self.titleLabel.font.fontName;
}

- (void)setFontName:(NSString *)fontName{
    self.titleLabel.font = [UIFont fontWithName:fontName size:self.titleLabel.font.pointSize];
}
@end
  1. Setting the font in the storyboard: In User Defined Runtime Attributes, set the key path to fontName, the type to String, and the value to the font’s PostScript name (often different from the file name).

This will set your custom font while running the app.

Notes:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents