Custom Fonts with Storyboard

suggest change

Custom Fonts for UI components from storyboard can be easily achieved with User Defined Runtime Attributes in storyboard and Categories.

The advantages are like,

Steps to follow
  1. Font File: Add the Font file (.ttf) to the application bundle and add the entry for the font in Info.plist under Font provided by application as in this documentation of custom fonts.
  2. Define Categories: Add a file like UIKit+IBExtensions and add the categories for UI elements like UILabel, UIButton etc. for which you want to set custom font. All the categories will be having a custom property say fontName. This will be using from the storyboard later for setting custom font (as in step 4).

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 getters and setters for the fontName property towards each category added.

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 font in storyboard: Add an entry in User Defined Runtime Attributes with fontName as keyPath and your Custom Font’s Name as value with type as String as shown.

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