更新:Xcode 6的Interface Builder现在允许您选择自定义字体,并在设计时正确呈现。
我知道这个问题很老,但我一直在努力寻找一种在iOS 5中轻松指定Storyboard(或Interface Builder)自定义字体的方法,我找到了一个相当方便的解决方案。
首先,请确保按照此教程将字体添加到项目中。还要记住,可以使用UIAppearance代理的setTitleTextAttributes:
方法来指定UINavigationBar、UITabBar和UISegmentedControl的自定义字体。
为UIButton、UITextField、UILabel和任何其他需要自定义字体的组件添加以下类别。这些类别只是实现了一个新属性fontName
,它会改变元素的当前字体,同时保持字体大小不变。
要在Storyboard中指定字体,只需选择所需的元素(标签、按钮、文本视图等),并添加一个
用户定义的运行时属性,其中
键路径设置为
字符串类型的
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
也可从GIST下载,链接如下:
单个文件和
多个文件。
故障排除
如果您运行时遇到fontName
属性未指定的运行时错误,请在项目设置中添加标志-all_load
到其他链接器标志下,以强制链接器包含类别。