Swift Custom Fonts Xcode
These are the steps to add a custom font to you application:
- Add "gameOver.ttf" font in your application ( Make sure that it's included in the target)
- Modify the application-info.plist file.
- Add the key "Fonts provided by application" in a new row
- and add "gameOver.ttf" as new item in the Array "Fonts provided by application".
Now the font will be available in Interface Builder.
To use the custom font in code we need to refer to it by name, but the name often isn’t the same as the font’s filename
There are 2 ways to find the name:
- Install the font on your Mac. Open Font Book, open the font and see
what name is listed.- Programmatically list the available fonts in your app
for the second approach add this line is your app delegate’s didFinishLaunchingWithOptions
print(UIFont.familyNames)
To list the fonts included in each font family, in Swift 5:
func printFonts() {
for familyName in UIFont.familyNames {
print("\n-- \(familyName) \n")
for fontName in UIFont.fontNames(forFamilyName: familyName) {
print(fontName)
}
}
}
after finding the name of your custom font you may use it like this:
SKLabelNode(fontNamed: "gameOver") // put here the correct font name
or in a simple label :
cell.textLabel?.font = UIFont(name: "gameOver", size: 16) // put here the correct font name
Useful resource
Use custom font in swift
Fist make sure that your font is .ttf or .otf format
- Import your font into the project
- Add new key "Fonts provided by application" on application's info.plist file and add your font names
Now you can use custom fonts with interface builder or programatically
yourLabel.font = UIFont.init(name: YourFont, size: size)
Adding custom font to Xcode 13+
- drag and drop your font-file into the project (make sure you hit copy if needed and check the target box)
- choose Project -> Targets -> Info -> Custom iOS Target Properties and klick the small + icon under the "key" property. Start typing "Fonts provided by application"
- enter the full font-filename inside this property-list
now you can use the font by its name
(Bonus: if you have trouble to find the font name, you can print all available fonts with [see detail explanation for this at code with chris ]:
for family: String in UIFont.familyNames
{
print(family)
for names: String in UIFont.fontNames(forFamilyName: family)
{
print("== \(names)")
}
}
Swift 4 set custom font programmatically
You can try
lbl.font = UIFont(name:"FontAwesome",size:15)
the name should be the font name as it is when you install it . not as the file name in your case was Noto Kufi Arabic instead of NotoKufiArabicRegular
click the font and open it with Font Book , then install it after that specify exactly the name shown in the parameter in the line above
How to use a custom font in an entire IOS app the right way
Based on this site and making some adjustments
First: You must add your fonts in your project and add them in the info.plist
file:
https://codewithchris.com/common-mistakes-with-adding-custom-fonts-to-your-ios-app/
File: UIFont.swift
import Foundation
import UIKit
struct AppFontName {
static let regular = "Montserrat-Regular"
static let bold = "Montserrat-Bold"
static let lightAlt = "Montserrat-Light"
}
//customise font
extension UIFontDescriptor.AttributeName {
static let nsctFontUIUsage = UIFontDescriptor.AttributeName(rawValue: "NSCTFontUIUsageAttribute")
}
extension UIFont {
@objc class func mySystemFont(ofSize size: CGFloat) -> UIFont {
return UIFont(name: AppFontName.regular, size: size)!
}
@objc class func myBoldSystemFont(ofSize size: CGFloat) -> UIFont {
return UIFont(name: AppFontName.bold, size: size)!
}
@objc class func myItalicSystemFont(ofSize size: CGFloat) -> UIFont {
return UIFont(name: AppFontName.lightAlt, size: size)!
}
@objc convenience init(myCoder aDecoder: NSCoder) {
guard
let fontDescriptor = aDecoder.decodeObject(forKey: "UIFontDescriptor") as? UIFontDescriptor,
let fontAttribute = fontDescriptor.fontAttributes[.nsctFontUIUsage] as? String else {
self.init(myCoder: aDecoder)
return
}
var fontName = ""
switch fontAttribute {
case "CTFontRegularUsage":
fontName = AppFontName.regular
case "CTFontEmphasizedUsage", "CTFontBoldUsage":
fontName = AppFontName.bold
case "CTFontObliqueUsage":
fontName = AppFontName.lightAlt
default:
fontName = AppFontName.regular
}
self.init(name: fontName, size: fontDescriptor.pointSize)!
}
class func overrideInitialize() {
guard self == UIFont.self else { return }
if let systemFontMethod = class_getClassMethod(self, #selector(systemFont(ofSize:))),
let mySystemFontMethod = class_getClassMethod(self, #selector(mySystemFont(ofSize:))) {
method_exchangeImplementations(systemFontMethod, mySystemFontMethod)
}
if let boldSystemFontMethod = class_getClassMethod(self, #selector(boldSystemFont(ofSize:))),
let myBoldSystemFontMethod = class_getClassMethod(self, #selector(myBoldSystemFont(ofSize:))) {
method_exchangeImplementations(boldSystemFontMethod, myBoldSystemFontMethod)
}
if let italicSystemFontMethod = class_getClassMethod(self, #selector(italicSystemFont(ofSize:))),
let myItalicSystemFontMethod = class_getClassMethod(self, #selector(myItalicSystemFont(ofSize:))) {
method_exchangeImplementations(italicSystemFontMethod, myItalicSystemFontMethod)
}
if let initCoderMethod = class_getInstanceMethod(self, #selector(UIFontDescriptor.init(coder:))), // Trick to get over the lack of UIFont.init(coder:))
let myInitCoderMethod = class_getInstanceMethod(self, #selector(UIFont.init(myCoder:))) {
method_exchangeImplementations(initCoderMethod, myInitCoderMethod)
}
}
}
AppDelegate.swift
override init() {
super.init()
UIFont.overrideInitialize()
}
Usage:
label.font = UIFont.boldSystemFont(ofSize: 16)
label.fontUIFont.systemFont(ofSize: 12)
How do i setup custom font
So i figured out the problem. Which seems like an Xcode bug?
I noticed that if i first put the Font onto a label in a storyboard (i'm doing everything programmatically). It was actually loaded into the font family. I don't know why i have to add it in a storyboard. But as dumb as it is here is my solution:
Guess it's the most ugly solution i have ever seen, but it works, and i can't find another way.
Custom Font in swift
This is pretty easy to do, actually. Firstly, you need to make sure that the font file is in your app file hierarchy:
you can see mine here "small_pixel.ttf"
Secondly you need to make sure that the info.plist
file has the EXACT file name as your custom font:
you can see that here.
Thirdly, you need to make sure that the font is included in bundle resources
you can navigate to it by going:
to add it to bundle resources
simply drag and drop the file into the hierarchy.
Finally you can see all of your fonts by doing...
for family in UIFont.familyNames {
print("Family: \(family)")
for name in UIFont.fontNames(forFamilyName: family) {
print(" - \(name)")
}
}
...in some function that gets called when you launch your app. Simply scroll down through the Debug area until you find your font.
(ps. this is from my first really trashy game. If you want to check it out, search "Crappy Duck" on the AppStore)
How to change font in Xcode Swift Playgrounds(.swiftpm) project?
I found the solution by myself with the help of a friend, I had to create a public struct MyFont with a fileprivate static func, and then add an init inside the main file, before var body.
This is the code:
MyFont
import SwiftUI
public struct MyFont {
public static func registerFonts() {
registerFont(bundle: Bundle.main , fontName: "YOUR-FONT-HERE", fontExtension: ".ttf") //change according to your ext.
}
fileprivate static func registerFont(bundle: Bundle, fontName: String, fontExtension: String) {
guard let fontURL = bundle.url(forResource: fontName, withExtension: fontExtension),
let fontDataProvider = CGDataProvider(url: fontURL as CFURL),
let font = CGFont(fontDataProvider) else {
fatalError("Couldn't create font from data")
}
var error: Unmanaged<CFError>?
CTFontManagerRegisterGraphicsFont(font, &error)
}
}
MyApp
@main
struct MyApp: App {
//add the init before var body
init() {
MyFont.registerFonts()
}
var body: some Scene {
//
}
}
Related Topics
Uibutton Borders Function Only Gives Back White Borders
Why Is Swift Giving Me Inaccurate Floating Point Arithmetic Results
Swift Applications Takes More Space on Disk
Aurendercallbackstruct in Swift
Sharing Button Works Perfectly on iPhone But Crash on Ipad
Check If Avaudioplayer Is Playing
How to Display an Alert Controller When Nsdate == to a Time (For Example 12:00 Am) in Swift
Swift Method Parameters in Documentation
How to Parse Url # Fragments with Query Items in Swift
How to Draw an Image in an Nsopenglview with Swift
Why Does My Swift Bundle Get The Wrong Principal Class
Swiftui: Unable to Animate Images
Implement a Crosshair Kind Behaviour in Realitykit
How to Create Generic Closures in Swift