Christopher Francisco
Christopher Francisco

Reputation: 16268

UIButton change border color in different states in swift

I'm adding an extension to UIButton so that it changes it border color when disabled/enabled

extension UIButton {
    override public var enabled: Bool {
        didSet {
            if enabled {
                changeBorderColorForEnabled()
            } else {
                changeBorderColorForDisabled()
            }
        }
    }
}

The issue is that sometimes the border color changes, but the title color doesn't.

Specifically, it happens when it changes too fast, like in the following piece of code, when it executes line //==== 1. =====// and //==== 2. =====//

       // Enabled by default
        self.priceButton.enabled = true   //==== 1. =====//

        if bought {
            self.priceButton.setTitle("bought", forState: UIControlState.Normal)
        } else {
            if let price = self.product?.price {
                self.priceButton.setTitle("Buy for \(price)", forState: UIControlState.Normal)
            } else {

                // Disable if price hasn't been retrieved
                self.priceButton.enabled = false   //==== 2. =====//
            }
        }

How can I fix this?

Upvotes: 2

Views: 1976

Answers (1)

matt
matt

Reputation: 534925

I'm going to guess that the problem is caused by the fact that, by interfering with UIButton's response to setEnabled:, you are drawing at the same time that the button is trying to draw - and that this is messing up the button's attempt to draw.

The first thing I would try is adding a short delay, to give the button a chance to do its own drawing first (for delay, see https://stackoverflow.com/a/24318861/341994):

    didSet {
        delay(0.1) {
            if enabled {
                changeBorderColorForEnabled()
            } else {
                changeBorderColorForDisabled()
            }
        }
    }

Upvotes: 1

Related Questions