Custom Fonts with Storyboard
suggest changeCustom Fonts for UI components from storyboard can be easily achieved with User Defined Runtime Attributes in storyboard and Categories.
The advantages are like,
- No need to define outlets for the ui element
- No need to set font for elements programatically.
Steps to follow
- 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.
- 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
- 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
- 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.
![](/essential/ios/img/cf3e1b88831b3e7baa7fb2fe366d8f42cde729cc.png)
This will set your custom font while running the app.
Notes:
- Lato-Regular is the custom font I have used.
- Same name in the .ttf file added in bundle should be used without extension in storyboard.
- Font size will be same as it is defined in the UI element’s attribute inspector.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents