Attempting to toggle both the selected and enabled attribute on a UIButton, therefore creating 4 potential states (Selected & Disabled, Selected & Enabled, Unselected & Disabled, unselected & Enabled).
In viewDidLoad I define the the images for the button states
- (void)viewDidLoad
{
[super viewDidLoad];
[self.inputToolbar.contentView.leftBarButtonItem setImage:[UIImage imageNamed:BLUE_IMAGE] forState:UIControlStateNormal];
[self.inputToolbar.contentView.leftBarButtonItem setImage:[UIImage imageNamed:GREY_IMAGE] forState:UIControlStateSelected];
}
In viewWillAppear I conditionally set the enabled attribute along with a property (we'll call self.buttonShouldBeSelected) which then sets the UIButton's selected attribute in its setter. Along with some debugging code in viewDidLoad
- (void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
// default control states
self.inputToolbar.contentView.leftBarButtonItem.enabled = NO;
if (self.aBoolean) {
self.buttonShouldBeSelected = [self.aNSNumber boolValue];
}
}
- (void)setButtonShouldBeSelected:(BOOL)buttonShouldBeSelected
{
self.inputToolbar.contentView.leftBarButtonItem.selected = buttonShouldBeSelected;
_buttonShouldBeSelected = buttonShouldBeSelected;
}
- (void)viewDidAppear
{
NSLog(@"SELECTED: %u", self.inputToolbar.contentView.leftBarButtonItem.selected);
NSLog(@"ENABLED: %u", self.inputToolbar.contentView.leftBarButtonItem.enabled);
NSLog(@"STATE: %lu", self.inputToolbar.contentView.leftBarButtonItem.state);
}
This works in all cases aside from one, when the button is disabled and in the selected state. In this case the UI displays the BLUE_IMAGE instead of the selected state's GREY_IMAGE and the button is correctly disabled.
In this case the log results in...
SELECTED: 1
ENABLED: 0
STATE: 6
What am I doing wrong, why is it showing the image for NormalState and what does UIControlState == 6 mean?
And for Swift 3:
inputToolbar.contentView.leftBarButtonItem.setImage(UIImage(named: GREY_IMAGE), for: [.disabled, .selected])
I have come in to the same problem. I used property isUserInteractionEnabled instead of isEnabled, so the button can remain status where it was before.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With