Jason
Jason

Reputation: 1067

Swift: How to subclass a UIButton?

I want a simple class that changes the colour of background and text on a button when its selected.

I have got this :

class buttonSelected : UIButton {        
    override var highlighted: Bool {
        get {
            return super.highlighted

        }
        set {                
                backgroundColor = UIColor(red: 0.27, green: 0.29, blue: 0.31, alpha: 1.0)
                //backgroundColor = UIColor.whiteColor()
                setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
                println(tag)
                super.highlighted = newValue
        }
    }        
}

This subclassing works great. I manually add the tag to each individual button. First question is why does the

pritnln(tag)

show twice ?

Also whats the best way to revert this when the user presses on the button again. I cannot subclass highlighted again, and there is only selected, disabled left. I get this info by cmd over the highlighted text.

Upvotes: 1

Views: 1918

Answers (1)

Zell B.
Zell B.

Reputation: 10286

About the first question the println(tag) show twice because highlighted value change twice : firstly when button is clicked (its value become true) and secondly when click is released (its value become false)

About the second question the best way to reach what you are looking for I think is by overriding selected var and set the colors on its set method based on newValue, but to reach that you have to change selected value somehow and my first thought is by using the highlighted var that you already override by doing so

override var highlighted: Bool {
    get {
        return super.highlighted

    }
    set {

            if(newValue){
                self.selected = !self.selected
            }
            super.highlighted = newValue
    }
}

Upvotes: 2

Related Questions