标签:blog http io ar os 使用 sp for strong
FZLanTingHei-R-GBK.TTF和FZLanTingHei-DB-GBK.TTF(粗体)
完成这一步后,可以在程序中打印出支持的字体,看是否添加成功:
NSArray *familyNames = [UIFont familyNames]; for( NSString *familyName in familyNames ){ printf( "Family: %s \n", [familyName UTF8String] ); NSArray *fontNames = [UIFont fontNamesForFamilyName:familyName]; for( NSString *fontName in fontNames ){ printf( "\tFont: %s \n", [fontName UTF8String] ); } }
此例子的字体为方正准圆,通过上一步的函数打印出来的字体字符串:
UIFont *font = [UIFont fontWithName:@"FZLanTingHei-R-GBK" size:16];
self.nameField.font = font;
此方法适用于所有调用systemFont, boldSystemFont时使用的字体
+ (void)installCustomFont{ s_sysFontName = [UIFont systemFontOfSize:10].fontName; //获取系统字体名称 s_boldSysFontName = [UIFont boldSystemFontOfSize:10].fontName; //获取系统粗体字体名称 //替换系统的systemFont方法 SEL systemFontSelector = @selector(systemFontOfSize:); Method oldMethod = class_getClassMethod([UIFont class], systemFontSelector); Method newMethod = class_getClassMethod([self class], systemFontSelector); method_exchangeImplementations(oldMethod, newMethod); //exchange可用replace替代 //替换系统的boldSystemFont方法 SEL boldSystemFontSelector = @selector(boldSystemFontOfSize:); oldMethod = class_getClassMethod([UIFont class], boldSystemFontSelector); newMethod = class_getClassMethod([self class], boldSystemFontSelector); method_exchangeImplementations(oldMethod, newMethod); //exchange可用replace替代 } + (UIFont *)systemFontOfSize:(CGFloat)fontSize{ UIFont *font = [UIFont fontWithName:@"FZLanTingHei-R-GBK" size:fontSize]; return font; } + (UIFont *)boldSystemFontOfSize:(CGFloat)fontSize{ UIFont *font = [UIFont fontWithName:@"FZLanTingHei-DB-GBK" size:fontSize]; return font; }
该方法只对调用installCustomFont之后的systemFont, boldSystemFont有效,所以应该在AppDelegate中初始化程序的时候调用该方法。
如果需要,可以再加上UITextView/UITextField等。
-(void)setCustomFontForView:(UIView*)aView{ if ([aView isKindOfClass:[UILabel class]]){ UILabel *label = (UILabel *)aView; if([label.font.fontName isEqual:s_sysFontName]){//替换普通 label.font = [UIFont systemFontOfSize:label.font.pointSize]; } else if([label.font.fontName isEqual:s_boldSysFontName]){//替换粗体 label.font = [UIFont boldSystemFontOfSize:label.font.pointSize]; } } for (UIView *sview in aView.subviews) { [self setCustomFontForView:sview]; } }
对于UITableView,ViewDidLoad的时候还未加载,而且不能通过UItableView的subView遍历每个Cell,因此要在willDisplayCell时候调用上边的方法修改字体:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{ [self setCustomFontForView:cell]; }
标签:blog http io ar os 使用 sp for strong
原文地址:http://www.cnblogs.com/zhongriqianqian/p/4139269.html