use*_*642 3 iphone fonts objective-c ios swift
我想在iOS应用程序中保留自定义字体.目前,我使用的是iOS默认字体.有没有可能的方法呢?
如何包含自定义字体以便我可以使用它?
Xei*_*han 14
制作一个类别:
#import "UILabel+Helper.h"
@implementation UILabel (Helper)
- (void)setSubstituteFontName:(NSString *)name UI_APPEARANCE_SELECTOR {
self.font = [UIFont fontWithName:name size:self.font.pointSize]; }
@end
Run Code Online (Sandbox Code Playgroud)
然后在AppDelegate.m中:
[[UILabel appearance] setSubstituteFontName:@"SourceSansPro-Regular"];
Run Code Online (Sandbox Code Playgroud)
这将在整个应用程序甚至更改字体UIButton,UILabel,内UITableViewCell,UICollectionViewCell,UIView,UIContainerView,或者在申请中任何地方而不改变字体点大小.
这是一种内存有效的方法,而不是枚举你的所有视图UIViewController.
将您的字体文件复制到资源中
在您的Info.plist文件中添加一个密钥UIAppFonts.("申请提供的字体")
将此键设为数组
对于您拥有的每种字体,请输入字体文件的全名(包括扩展名)作为UIAppFonts数组的项目
保存Info.plist
现在,在您的应用程序,你可以简单地调用下面的方法来让你使用自定义的字体UILabel和UITextView等...
[UIFont fontWithName:@"CustomFontName" size:15];
func allFonts(){
for family in UIFont.familyNames(){
println(family)
for name in UIFont.fontNamesForFamilyName(family.description)
{
println(" \(name)")
}
}
}
Run Code Online (Sandbox Code Playgroud)
UILabel:在AppDelegate.m中添加代码
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
...
[[UILabel appearance] setFont:[UIFont fontWithName:@"YourFontName" size:17]];
...
}
Run Code Online (Sandbox Code Playgroud)
viewConroller与视图设计中设置的字体大小相同:- (void)viewDidLoad
{
[super viewDidLoad];
[self setFontFamily:@"YourFontName" forView:self.view andSubViews:YES];
}
-(void)setFontFamily:(NSString*)fontFamily forView:(UIView*)view andSubViews:(BOOL)isSubViews
{
if ([view isKindOfClass:[UILabel class]])
{
UILabel *lbl = (UILabel *)view;
[lbl setFont:[UIFont fontWithName:fontFamily size:[[lbl font] pointSize]]];
}
if (isSubViews)
{
for (UIView *sview in view.subviews)
{
[self setFontFamily:fontFamily forView:sview andSubViews:YES];
}
}
}
Run Code Online (Sandbox Code Playgroud)