Search code examples
swiftuibuttonuifont

How do I set the weight of the font of a titleLabel of a UIButton?


I'm changing the font of the title of a UIButton like this:

self.titleLabel?.font = UIFont(name: "SF UI Display", size: 30)

How do I then change the weight (I think XCode calls it "style")? It is currently defaulting to medium and I need it to be regular.


Solution

  • You can Download the The Regular Font

    Try printing the Font Name:

     func printFonts() {
        let fontFamilyNames = UIFont.familyNames
        for familyName in fontFamilyNames {
            print("------------------------------")
            print("Font Family Name = [\(familyName)]")
            let names = UIFont.fontNames(forFamilyName: familyName)
            print("Font Names = [\(names)]")
        }
    }
    

    and then set it as follows:

    self.titleLabel?.font = UIFont(name: "pass the name of downloaded file", size: 30) //Pass the name of downloaded file here
    

    Note:- After Downloading and Drag and Dropping into your Project, Do not forget to check the Target Membership is ticked or not, if not then tick it or it will not work for you

    Edit For setting appropriate name

    Remove the existing font file by moving into trash and then

    Change the file name after downloading to SFUIDisplayRegular.otf

    the tick the target membership

    self.titleLabel?.font =  UIFont(name: "SFUIDisplayRegular", size: 20)
    

    And it will work for you,

    Cheers!

    See the Output:

    enter image description here