How to change font of UIButton with Swift

i0S Swift Issue

Question or problem with Swift language programming:

I am trying to change the font of a UIButton using Swift…

myButton.font = UIFont(name: "...", 10)

However .font is deprecated and I’m not sure how to change the font otherwise.

Any suggestions?

How to solve the problem:

Solution 1:

Use titleLabel instead. The font property is deprecated in iOS 3.0. It also does not work in Objective-C. titleLabel is label used for showing title on UIButton.

myButton.titleLabel?.font =  UIFont(name: YourfontName, size: 20)

However, while setting title text you should only use setTitle:forControlState:. Do not use titleLabel to set any text for title directly.

Solution 2:

For Swift 3.0:

button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)

where “boldSystemFont” and “16” can be replaced with your custom font and size.

Solution 3:

Dot-notation is awesome (swift 4.2) 👌
btn.titleLabel?.font = .systemFont(ofSize: 12)

Solution 4:

You don’t need to force unwrap the titleLabel to set it.

myButton.titleLabel?.font = UIFont(name: YourfontName, size: 20)

Since you’re not using the titleLabel here, you can just optionally use it and if it’s nil it will just be a no-op.

I’ll also add as other people are saying, the font property is deprecated, and make sure to use setTitle:forControlState: when setting the title text.

Solution 5:

From the documentation:


The font used to display text on the button. (Deprecated in iOS 3.0. Use the font property of the titleLabel instead.)

Hope this helps!