Reputation: 487
I'm using UIFont to change the default font in my app. the code is working fine on iOS 10 and below but it returns nil on iOS 11 , nothing has changed . I'm using swift 4
this is my code that returning nil :
UIFont(name: "AIranianSans", size: 20)
could you help me ? what is wrong ?
Upvotes: 5
Views: 2522
Reputation: 179
https://codewithchris.com/common-mistakes-with-adding-custom-fonts-to-your-ios-app/ After following steps mentions here, i was not able to load font in the application at runtime in swift4. Font will be appearing at runtime when we apply that particular custom font in story board. then only this api
UIFont(name: "font name", size: 20.0)
returning font instance otherwise it will be returning nil only. so design time custom font working fine but not runtime
to work runtime we need to load font
load font file as many you like
UIFont.registerFontWithFilenameString(filenameString: "font 1 Sans LF Bold.ttf", bundle: Bundle.main)
UIFont.registerFontWithFilenameString(filenameString: "font 2Sans LF Light.ttf", bundle: Bundle.main)
UIFont.registerFontWithFilenameString(filenameString: "font 3Sans LF Regular.ttf", bundle: Bundle.main)
UIFont.registerFontWithFilenameString(filenameString: "font 4Sans LF Medium.ttf", bundle: Bundle.main)
public static func registerFontWithFilenameString(filenameString: String, bundle: Bundle) {
guard let pathForResourceString = bundle.path(forResource: filenameString, ofType: nil) else {
print("UIFont+: Failed to register font - path for resource not found.")
return
}
guard let fontData = NSData(contentsOfFile: pathForResourceString) else {
print("UIFont+: Failed to register font - font data could not be loaded.")
return
}
guard let dataProvider = CGDataProvider(data: fontData) else {
print("UIFont+: Failed to register font - data provider could not be loaded.")
return
}
guard let fontRef = CGFont(dataProvider) else {
print("UIFont+: Failed to register font - font could not be loaded.")
return
}
var errorRef: Unmanaged<CFError>? = nil
if (CTFontManagerRegisterGraphicsFont(fontRef, &errorRef) == false) {
print("UIFont+: Failed to register font - register graphics font failed - this font may have already been registered in the main bundle.")
}
code is taken Xcode: Using custom fonts inside Dynamic framework
Upvotes: 0
Reputation: 9484
It looks like a custom font which you must have added as a resource in XCode. XCode 9 has a known issue of not adding resources to target when you include resources by drag and drop.
Check the target membership of your .ttf file in the file inspector.
Upvotes: 8
Reputation: 3708
Try to check the available fonts
for familyName:String in UIFont.familyNames {
print("Family Name: \(familyName)")
for fontName:String in UIFont.fontNames(forFamilyName: familyName) {
print("--Font Name: \(fontName)")
}
}
May be the font spelling is different.
Upvotes: 8