Jovan Angelov
Jovan Angelov

Reputation: 111

UIButton TitleLabel - How to set UIButton's font when titleLabel is nil?

I am trying change the font of a button class (before the button is initiated), but it does not work. It seems that the "titleLabel" is the issue since it is nil.

guard let object = NSClassFromString(button.key) as? UIButton.Type else { return }
let buttonClass = object.self

buttonClass.appearance().titleLabel?.text = UIFont(name: "HelveticaNeue-Thin", size: 20)

Here the titleLabel is nil, so it won't work.

I have also tried setting the label's font in my class (MBButton is my class), but this does not work as well

UILabel.appearance(whenContainedInInstancesOf[MBButton.self]).font = UIFont(name: "HelveticaNeue-Thin", size: 20)

Upvotes: 0

Views: 722

Answers (2)

DonMag
DonMag

Reputation: 77423

You can set the title label's font in your subclassed buttons setup:

@IBDesignable
class MMButton: UIButton {
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        commonInit()
    }
    func commonInit() -> Void {
        titleLabel?.font = UIFont(name: "HelveticaNeue-Thin", size: 20)
        // other customization here...
    }
}

Alternatively, if you want to use the .appearance() method, add an extension:

class MMButton: UIButton {
    // whatever you're doing for customization
}

extension MMButton {
    @objc dynamic var titleLabelFont: UIFont! {
        get { return self.titleLabel?.font }
        set { self.titleLabel?.font = newValue }
    }
}

then,

MMButton.appearance().titleLabelFont = UIFont(name: "HelveticaNeue-Thin", size: 20)

Upvotes: 1

Paul Schröder
Paul Schröder

Reputation: 1540

The best would be doing was @DonMag said. If you insist on using appearance, then you need to set titleFont on buttonClass.appearance() instead of titleLabel?.text

Upvotes: 0

Related Questions