Logunath
Logunath

Reputation: 477

Custom fonts not working in Swift programmatically but working with xib/Storyboard

I am using a custom font in my application. I added the fonts "ttf" file to the resource folder and made it available for all the target. I verified, it was in the copy bundle resource and in the plist file with proper naming conventions.

I used FontBook Mac app to take the PostScript name of the custom font and copy pasted to my code to avoid type errors.

I'm able to select the font in Storyboard/xib and its reflecting in the UI. But when I tried to do it programmatically like without using designers like below the font is not reflected in the UI.

The notable point here is I have 4 buttons and if I set font for one button via storyboard and set the same font for other buttons via programmatically, then its working.

  exploreAppBtn.titleLabel?.font =  UIFont(name: "SansOfcMed-Bold", size: 20)

Is it an Xcode issue? Anyone have faced it? If yes, whats the solution?

Added the Plist file and Build phases screenshots

enter image description here

enter image description here

Any help is appreciated! Thanks

Upvotes: 2

Views: 2177

Answers (3)

zef_s
zef_s

Reputation: 55

I tried more than 25 fonts, probably Swift does not support some fonts.(possibly a localization problem?)

  • ✅ Google Fonts work.
  • ✅ Cyrillic fonts work.

But custom fonts with a non-standard style or style/effect are not displayed at all.

Upvotes: 0

Sourabh Kumbhar
Sourabh Kumbhar

Reputation: 1054

  1. Check if custom font is added in info.plist file with proper naming conventions.
  2. Add extension

    extension UIFont {
        class func fontName(size: CGFloat) -> UIFont {
            return UIFont.init(name: "CustomFontName", size: size)!
         }
    }
    

Usage:

exploreAppButton.titleLabel?.font =  UIFont.fontName(size: 16)

Upvotes: 2

Gkolunia
Gkolunia

Reputation: 92

Could you please clarify how exactly you create CustomFontName

Maybe the font name is not valid

Valid fonts name you can find with the code.

let familyFontsNames = UIFont.familyNames

for familyName in familyFontsNames {
    let fontsName = UIFont.fontNames(forFamilyName: familyName)
    for fontName in fontsName {
        print(fontName) // Prints list of all available fonts name. And you should use the name.
    }
}

Try to check if your CustomFontName exists in the list.

Upvotes: 0

Related Questions