Fonts are an important element of personalization in software development, and the system comes with a lot of rich fonts, but sometimes it doesn't meet the needs of personalization, when you can add custom system fonts to your project and then use them just like you would with system fonts. Font files are most commonly used in formats such as TTF.
Importing a custom font process is simple: add a resource bundle to the project, register fonts in the Info.plist file, copy the font resource bundle in the project bundle resource, and then use the Code detection query to add the fonts
Add a resource bundle
AddFile Add a font resource bundle or drag the font package directly under the Project Resources folder:
Registering fonts in the Info.plist file
Add an array property to the project's Info.plist property list Fonts provided by application and add the custom font entry below it. Note that here in the Plist file is written in the full name of the file, including the file suffix, the name of the file can be changed, but it is recommended to use the original font family name, for example, here is: KRISTENITC, the font family name is not changed, This is followed by the font family name instead of the custom file name used in the specific code. The original font family name can be right-click to see the font file details, the full name is the original font family name, and the names are custom.
Copy resource bundle to bundle Resource
Detects if the font was successfully added
Before we use it, we can print out all of the system's font lists through the functions provided by the Uifont class, and find out if we have added more fonts to see if we can add success or not, but also see what specific font styles are in our resource pack, such as italic, bold, bold italic, and so on for the font family. The code for printing the font family list is as follows:
/** * 检查自定义字体族是否成功加入 */ // 取出系统安装了的所有字体族名 NSArray *familyNames = [UIFont familyNames]; NSLog(@"系统所有字体族名:%@", familyNames); // 打印字体族的所有子字体名(每种字体族可能对应多个子样式字体,例如每种字体族可能有粗体、斜体、粗斜体等等样式) for(NSString *familyName in familyNames) { // 字体族的所有子字体名 NSArray *detailedNames = [UIFont fontNamesForFamilyName:familyName]; NSLog(@"\n字体族%@的所有子字体名:%@", familyName,detailedNames); }
Here you can find the font family KRISTENITC we just added from the list of font groups:
and font family KRISTENITC under the specific font style, there is only one is the default one: Kristenitc-regular:
Using fonts
Make sure the font is joined to the system and can be used directly as a system font:
// 设置label的字体和大小(这里直接使用字体族名也是可以的,有默认的子字体样式,也可以根据需求具体到自字体比如这里的:KristenITC-Regular) [_label setFont:[UIFont fontWithName:@"KristenITC" size:35.0]];
"iOS Meditations" ios Add custom font description