2

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?

Christopher Francisco
  • 13,553
  • 23
  • 77
  • 181
  • It has nothing to do with _fast_. It has to do with _logic_. You are saying to set `enabled` to false so it is set to `false`. What does this have to do with "title color" anyway? I see no "title color" in your code. And since you don't show `changeBorderColorForEnabled`, no one knows what you might be doing there. If you want help, show your code; don't _conceal_ it. – matt May 25 '15 at 16:27
  • when you change the state to enabled = false, by default, the title color changes – Christopher Francisco May 25 '15 at 21:28
  • Okay, I'm with you. And what precisely goes wrong? Is it that the button is disabled but the title does not go gray? – matt May 25 '15 at 22:18
  • Exactly, the button is disabled, but the title doesn't go gray. But this only happens in the sequence. If I just disable it, the text DO go gray – Christopher Francisco May 28 '15 at 13:42

1 Answers1

1

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()
            }
        }
    }
Community
  • 1
  • 1
matt
  • 447,615
  • 74
  • 748
  • 977