I am trying to change font size of button itself after it was pressed.
class ViewController: UIViewController {
@IBOutlet weak var buttonToResize: UIButton!
@IBAction func buttonTapped(_ sender: UIButton) {
buttonToResize.titleLabel!.font = UIFont(name: "Helvetica", size: 40)
// Also tried buttonToResize.titleLabel?.font = UIFont .systemFont(ofSize: 4)
}
However the changes are not applied.
What is interesting, to me, that if I try to resize some other button (second one) after pressing on initial (first one), it works as expected.
Like this:
class ViewController: UIViewController {
@IBOutlet weak var buttonToResize: UIButton!
@IBOutlet weak var secondButtonToResize: UIButton!
@IBAction func buttonTapped(_ sender: UIButton) {
secondButtonToResize.titleLabel!.font = UIFont(name: "Helvetica", size: 40)
}
Other properties like backgroundColor seems to apply, however with font size I face problem.
4
Answers
You probably want something like this
First, here’s the sequence of events when you tap on a
UIButton
.isHighlighted
property totrue
.Touch Down
actions, possibly multiple times if you drag your finger around.Primary Action Triggered
actions (like yourbuttonTapped
).Touch Up
actions.isHighlighted
property tofalse
.Every time isHighlighted changes, the button updates its styling to how it thinks it should look. So a moment after
buttonTapped
, the button you pressed overwrites your chosen font with its own font.It’s worth exploring this to make sure you understand it by creating a
UIButton
subclass. Don’t use this in production. Once you start overriding parts of UIButton, you need to override all of it.So where does it keep pulling its old font from? On loading a view it will apply UIAppearance settings, but those will get discarded when you press the button too. iOS 15+, it looks like it uses the new UIButton.Configuration struct. So you could put this in your
buttonTapped
:I’d like to think there’s a simpler way to do this. Whichever way you work, make sure it will also work in the event of other changes to your button, such as some other event setting
isEnabled
tofalse
on it.This should solve the problem. Use the sender tag instead of the IBOutlet.
Cowirrie analysis made me think of this solution (tested)