custom font not working programmatically in swift

I've followed the step to to add custom fonts in xcode at swift day-by-day and custom fonts but I'm not able to set that font in app label programmatically.

var labeladd = UILabel(frame: CGRectMake(40, 50, 70, 22))
    //  label.center = CGPointMake(160, 284)
 ///  labeladd.font=UIFont.boldSystemFontOfSize(15)
   labeladd.font = UIFont(name:"Source Sans Pro",size:15)
    labeladd.textColor=UIColor.blackColor()
    labeladd.textAlignment = NSTextAlignment.Center
    labeladd.text = "this is custom fonts"
    myview.addSubview(labeladd)

Let's say you want to add this font: SourceSansPro-Regular.otf

Four steps:

  1. Add the font file SourceSansPro-Regular.otf to your project, make sure you select your target in the "Add to targets".

enter image description here

Go to the target's Build Phases and make sure it is under Copy Bundle Resources. If not, add it.

enter image description here



2. Go to the target's Info. Add a new entry Font provided by application then add a new item with this value SourceSansPro-Regular.otf.

enter image description here



  1. From your finder, double click on the file SourceSansPro-Regular.otf, it might ask you to install the font to your Font Book.



  1. Open the OS X Font Book application, navigate to your font then press Command+i. Note the PostScript name and use that name in your Swift code. In this case, it's SourceSansPro-Regular. enter image description here



So in your code:

labeladd.font = UIFont(name:"SourceSansPro-Regular", size:15)


I've found (XCode 12) that unless your font happens to be already used in your Main.storyboard, that even if you have done all the correct steps of registering the font file in your app, copied to your bundle resources, used the PostScript name, yadda, yadda, that it still didnt show up and trying to use it in UIFont(name: size:) would still return nil. :-(

I worked around this current bug (?) by manually registering all my custom fonts at startup in AppDelegate application(_ application: didFinishLaunchingWithOptions:)

let fonts = Bundle.main.urls(forResourcesWithExtension: "ttf", subdirectory: nil)
fonts?.forEach({ url in
    CTFontManagerRegisterFontsForURL(url as CFURL, .process, nil)
})

(adapted from Xcode: Using custom fonts inside Dynamic framework)