Reputation: 1435
I am trying to find the best approach to doing this. I have 5 custom buttons on a view controller and I am trying to have the button stay highlighted if it is clicked. I know how to do this but I am trying to only allow 1 button to be highlighted at a time. So if a user clicks a button and highlights it, but clicks another, then the most recent button clicked will stay highlighted and the previous will unhighlight. What would be the best way to accomplish this?
Upvotes: 1
Views: 6002
Reputation: 7410
You should keep a reference to all your buttons (for example, if you use IB, have links in your code like @property (nonatomic, strong) IBOutlet UIButton *button1;
for all your buttons).
Then link all your buttons to the same method for a press on the button. I'll call it buttonPressed
.
Impement it like this :
- (IBAction)buttonPressed:(id)sender {
UIButton *buttonPressed = (UIButton*)sender;
NSArray *buttons = [NSArray arrayWithObjects:_button1, _button2, _button3, nil];
bool buttonIsHighlighted = NO;
// Check if a button is already highlighted
for (UIButton *button in buttons) {
if (button.highlighted) {
buttonIsHighlighted = YES;
}
}
// If a button is highlighted, un-highlight all except the one pressed
// If no button is highlighted, just highlight the right one
if (buttonIsHighlighted) {
for (UIButton *button in buttons) {
if (buttonPressed == button) {
buttonIsHighlighted = YES;
} else {
button.highlighted = NO;
}
}
} else {
buttonPressed.highlighted = YES;
}
}
I can't test this code but I'm pretty sure it should work. Let me know if something's wrong.
Upvotes: 3
Reputation: 7921
Solution 1:
Put your buttons in an NSArray
and when user clicks on a button check if another is highlighted. If YES
, unhighlight it and highlight the one was pressed. If NO
, highlight directly the one pressed.
Solution 2:
You can save the highlighted button in a global variable declared in @interface
or in a @property
. When users click the new one unhighlight the previous.
Upvotes: 0