Determine which button is pressed using the UIButton array

I have a UIButton array like this:

@property (nonatomic, retain) IBOutletCollection(UIButton) NSArray *btn_Impact_Collection; 

and I have this function:

 - (IBAction)impactAction:(id)sender; 

I have nine buttons in the XIB file, each button is connected to the btn_Impact_Collection array using a collection of referenced outputs. In addition, the Touch_inside property of each button is connected to the ImpactAction function.

Now that the button is pressed, the ImpactAction function is called, but inside this function, how can I find out which button is pressed?

Thanks in advance for your reply!

+6
source share
4 answers

Send the sender to the UIButton class and this will give you an instance of the button clicked. I don't have Xcode with me, but something like:

 if ([sender isMemberOfClass:[UIButton class]]) { UIButton *btn = (UIButton *)sender; // Then you can reference the title or a tag of the clicked button to do some further conditional logic if you want. if([btn.currentTitle isEqualToString:@"title of button"]) { // do something. } else if(etc...) } 
+14
source

Set tags for each button in the interface builder (1-9), then say

 if ([sender tag] == 1) { //First button was pressed, react. } else if ([sender tag] == 2) { //Second button was pressed, react. } // Etc... else { //Last button was pressed, react. } 

And the same goes for everyone else, or you can put it in a switch.

+13
source

Instead of doing a line-by-line header check (which is slow and can be tedious), you can:

 - (void)buttonPressed:(id)sender { for( UIButton *button in self.buttonCollection ) { if( sender == button ) { // sender is your button (eg. you can access its tag) } } } 
+3
source

Another option .. Send the sender to check if it has a UIButton, then switch sender.tag:

 if ([sender isMemberOfClass:[UIButton class]]) { switch ([sender tag]) { case 0: //do stuff for button with tag 0 break; case 1: //do stuff for button with tag 1 break; case 2: .... break; default: break; } } 
0
source

Source: https://habr.com/ru/post/893358/


All Articles