Search code examples
iosswiftuibuttonuilabel

How to auto-capitalize the label of a UIButton?


I'm working with a designer and we have a few different typefaces involved in the project, sometimes doing everything in all caps, sometimes all lower case. This applies to both my labels and buttons. These may change, so what I'm attempting to do is have custom UILabel and UIButton classes where the button title will be automatically adjusted to the case I want without regards to what capitalization is entered in the interface builder or text from code. I have successfully managed this with my custom labels with the following code:

class MyHeadlineLabel : UILabel {
    override func didMoveToWindow() {
        self.text = self.text?.lowercased()
        self.font = MyFonts.headlineFont
    }
}

However, adding similar code to the didMoveToWindow() function of UIButton does NOT work:

class MyDarkTextButton: UIButton {
    override func didMoveToWindow() {
        self.titleLabel?.text = self.titleLabel?.text?.uppercased()
        self.font = MyFonts.subHeadFont            
    }
}

How would I go about doing that? Or, better yet, is there a way to use my custom labels as the button labels?


Solution

  • You need to set title of button, not titleLabel's text directly. updated your code as follows:

    override func didMoveToWindow() {
        self.setTitle(self.title(for: .normal)?.uppercased(), for: .normal)
    }
    

    This code is working for me, I hope this will help you.