更新:Xcode 6 Interface Builder 现在允许您选择自定义字体并在设计时正确呈现它们。
我知道这个问题已经很老了,但我一直在努力寻找一种简单的方法来为 iOS 5 轻松地在 Storyboard(或 Interface Builder)中指定自定义字体,我找到了一个非常方便的解决方案。
首先,请确保您已按照this tutorial 将字体添加到项目中。还要记住,UINavigationBar、UITabBar 和 UISegmentedControl 自定义字体可以使用UIAppearance proxy 的setTitleTextAttributes: 方法指定。
为 UIButton、UITextField、UILabel 和任何其他需要自定义字体的组件添加以下类别。类别只是实现了一个新属性fontName,它改变了元素的当前字体,同时保持了字体大小。
要在 Storyboard 中指定字体,只需选择所需的元素(标签、按钮、文本视图等)并添加 用户定义的运行时属性,并将 Key Path 设置为String 类型的 fontName 和您的自定义字体名称的值。
就是这样,您甚至不需要导入类别。这样你就不需要为每个需要自定义字体的 UI 组件提供一个插座,也不需要手动编写代码。
考虑到字体不会显示在 Storyboard 中,但在您的设备或模拟器上运行时您会看到它。
分类文件
UIButton+TCCustomFont.h:
#import <UIKit/UIKit.h>
@interface UIButton (TCCustomFont)
@property (nonatomic, copy) NSString* fontName;
@end
UIButton+TCCustomFont.m:
#import "UIButton+TCCustomFont.h"
@implementation UIButton (TCCustomFont)
- (NSString *)fontName {
return self.titleLabel.font.fontName;
}
- (void)setFontName:(NSString *)fontName {
self.titleLabel.font = [UIFont fontWithName:fontName size:self.titleLabel.font.pointSize];
}
@end
UILabel+TCCustomFont.h:
#import <UIKit/UIKit.h>
@interface UILabel (TCCustomFont)
@property (nonatomic, copy) NSString* fontName;
@end
UILabel+TCCustomFont.m:
#import "UILabel+TCCustomFont.h"
@implementation UILabel (TCCustomFont)
- (NSString *)fontName {
return self.font.fontName;
}
- (void)setFontName:(NSString *)fontName {
self.font = [UIFont fontWithName:fontName size:self.font.pointSize];
}
@end
UITextField+TCCustomFont.h:
#import <UIKit/UIKit.h>
@interface UITextField (TCCustomFont)
@property (nonatomic, copy) NSString* fontName;
@end
UITextField+TCCustomFont.m:
#import "UITextField+TCCustomFont.h"
@implementation UITextField (TCCustomFont)
- (NSString *)fontName {
return self.font.fontName;
}
- (void)setFontName:(NSString *)fontName {
self.font = [UIFont fontWithName:fontName size:self.font.pointSize];
}
@end
也可下载from GIST 和a single file。
疑难解答
如果由于未指定 fontName 属性而遇到运行时错误,只需在项目设置的 Other linker Flags 下添加标志 -all_load 以强制链接器包含类别。