ButtonNode with enable

This is a follow-up to my previous ButtonNode post.  In this update I will be adding additional functionality to the button to allow the button to be enabled and disabled.

For this new functionality I want the ButtonNode to be able to do the following:

  • Maintain a boolean value indicating the current state of the button
  • Prevent the button from being clicked when it is disabled
  • Update the look of the button so that it appears to be disabled
  • Allow the button to toggled between the enabled and disabled state

To start we will simply add a new public property that represents the enable state of the button

@property (assign, nonatomic) BOOL enable;

Defining this property will automatically synthesize the getter and setter methods. But, since we want to change how the button looks and behaves when it is disabled we need to be able to execute code whenever the buttons’s enable property is set. The simplest way to do this is to create our own setter method which will be used instead of the auto-synthised setter.

// Setter for the enable property. Update the button based on the new state
– (void)setEnable:(BOOL)enable {

if (enable) {

self.userInteractionEnabled = YES;
self.alpha = 1.0;

} else {

self.userInteractionEnabled = NO;
self.alpha = 0.5;

}
_enable = enable;

}

In the setter method, when the button is being disabled, we set the userInteractionEnabled to NO and apply an alpha of 0.5 to dim the button. When the button is enable we simply reset the alpha to 1 and re-enable user interaction. Finally we update the underlying _enabled variable to track the state of the button.

The ButtonNode sample app, available on our github (ButtonNode) page, has been updated with this new functionality.

You can find me on twitter @mellowcoder

Posted in Coding and tagged , , , , , .