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.
What is the button style ? It doesn't work with custom buttons.
With custom buttons, you need to use AttributedTitle:
if let attrFont = UIFont(name: "Helvetica", size: 40) {
let title = buttonToResize.titleLabel!.text!
let attrTitle = NSAttributedString(string: title, attributes: [NSAttributedString.Key.font: attrFont])
buttonToResize.setAttributedTitle(attrTitle, for: UIControl.State.normal)
}
Note that this work also for non custom (system) button.