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?
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.
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.
From the documentation:
The font used to display text on the button. (Deprecated in iOS 3.0. Use the
font
property of thetitleLabel
instead.)
If you're having font size issues (your font isn't responding to size changes)...
@codester has the right code:
myButton.titleLabel!.font = UIFont(name: YourfontName, size: 20)
However, my font size wasn't changing. It turns out that I asking for a font that didn't exist ("HelveticaNeue-Regular"). It wasn't causing a crash, but seemed to be just ignoring that font statement because of it. Once I changed the font to something that does exist, changes to "size: x" did render.
we can use different types of system fonts like below
myButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
myButton.titleLabel?.font = UIFont.italicSystemFont(ofSize:UIFont.smallSystemFontSize)
myButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: UIFont.buttonFontSize)
and your custom font like below
myButton.titleLabel?.font = UIFont(name: "Helvetica", size:12)
Take a look here.
You should set the font of the button's titleLabel instead.
myButton.titleLabel!.font = UIFont(name: "...", 10)