PerNil
PerNil

Reputation: 187

Set font for UIButton with extension

I want to make it easy to change fonts and colors throughout my app. I have made a extension for UIButton like this:

extension UIButton {

    func cancelAndSaveButtons() {

        backgroundColor = Theme.tintColor
        layer.shadowOpacity = 0.25
        layer.shadowOffset = CGSize(width: 0, height: 10)
        layer.shadowRadius = 5
        layer.cornerRadius = frame.height / 2
        setTitleColor(Theme.mainFontColor, for: .normal)
        titleLabel?.font = UIFont(name: Theme.mainButtonFont, size: 25)

    }
  }   

And I have a class for the Theme:

class Theme {
    static let mainFontName = "BrushScriptMT"
    static let mainButtonFont = "FredokaOne"
    static let accentColor = UIColor(named: "Accent")
    static let backgroundColor = UIColor(named: "Background")
    static let tintColor = UIColor(named: "Tint")
    static let mainFontColor = UIColor(named: "MainFontColor")

}    

However, when I call myButton.cancelAndSaveButtons()in viewDidLoad the font or fontSize do not change. What am I missing here?

Upvotes: 0

Views: 131

Answers (1)

Marina Aguilar
Marina Aguilar

Reputation: 1189

You might be using the wrong font name. Add this code to your AppDelegate and check if you're using the right name:

for fontFamilyName in UIFont.familyNames {
        print("family: \(fontFamilyName)\n")

        for fontName in UIFont.fontNames(forFamilyName: fontFamilyName) {
            print("font: \(fontName)")
        }
    }

EDIT:

This is even cooler to print out the fonts:

dump(UIFont.familyNames)

Also, double check if you have imported your font files and added them to your plist. The font names on your plist must be the same as they will be printed on the code above.

Upvotes: 1

Related Questions