iosswift

how to set custom font with swift on ios


1.I copy ttf file to my project like this enter image description here

2.add to info.plist enter image description here

if let customFont = UIFont(name: "myFont", size: 54) {
        testLabel.font = customFont
    } else {
        print("Font loading failed!")
    }

it print Font loading failed! why? enter image description here

then i try to print all fonts like this:

for fontFamily in UIFont.familyNames {
       print(UIFont.fontNames(forFamilyName: fontFamily))
    }

But I couldn't find my custom font I don't know why, I am very grateful for the help


Solution

  • You can also check it from the storyboard. Select the custom fonts and see if your font is showing in the storyboard or not. I just tried the same thing, and it works with the same steps. Also, check the target membership of the font as well.

    Here is my code:

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        let testLabel: UILabel = UILabel()
        testLabel.center = CGPoint(x: 160, y: 285)
        testLabel.textAlignment = .center
        testLabel.text = "Hello World!"
        
        
        if let customFont = UIFont(name: "Lato", size: 54) {
                testLabel.font = customFont
            } else {
                print("Font loading failed!")
            }
        self.view.addSubview(testLabel)
    }