tHatpart
tHatpart

Reputation: 1136

UIButton subclass is changing font on click

I am seeing some weird behavior from an array of buttons I have built in storyboard. I have 4 buttons each of custom type TakesContainerButton and when a button is clicked it changes to the system font, but when a different button is clicked the previously button returns to the desired font, not sure what is going on here

The buttons are also embedded in a stack view, if that matters

Here is the the implementation when one of the buttons is pressed where buttons is an array of the 4 buttons

@IBAction func filterPressed(_ sender: TakesContainerButton) {
        for button in buttons {
            button.unclick()
        }
        sender.click()
    }

here is the custom class

class TakesContainerButton: UIButton {

        
        var bottom = UIView()
        
        func click(){
            self.setTitleColor(.darkGray, for: .normal)
            let xOffset:CGFloat = 10
            bottom = UIView(frame: CGRect(x: xOffset / 2, y: self.frame.height - 3, width: self.frame.width - xOffset, height: 3))
            bottom.layer.cornerRadius = 1.5
            bottom.backgroundColor = .darkGray
            self.addSubview(bottom)
        }
        
        func unclick(){
            bottom.removeFromSuperview()
            self.setTitleColor(UIColor(hex: "8B8B8B"), for: .normal)
        }
        
        override func awakeFromNib(){
            setFont()
        }
        
        func setFont(){
            self.titleLabel?.font = UIFont(name: "Lato-Bold", size: 12)
        }
    }

Upvotes: 4

Views: 1085

Answers (2)

THEJAS
THEJAS

Reputation: 109

In StoryBoard set button :

Type to Custom

Style to Default and

State Config to Default

you should have something like this

enter image description here

Upvotes: 3

Anubhav Giri
Anubhav Giri

Reputation: 509

Is there any specific reason that you are calling setFont() on every click. As I am able to see that you are not changing the font you should set this font at the time of view loading and leave the font as it is.

Upvotes: 0

Related Questions