IOS: 2 buttons name the same controller. How to find which one was pressed?

The title says most of what I'm looking for:

I have 2 buttons in the main menu that are called by the same controller. Depending on which button was pressed, the view controller behaves somewhat differently. I thought I had a fix using NSNotificationCenter, but it will not catch anything for the first time in the view controller (because it is not loaded yet). Are there any other ways to do this?


EDIT: There seems to be some kind of confusion, possibly on my part. The problem is the transfer of information through several controllers. Buttons in the main menu view controller CALL of the second view controller, the problem is that the second view controller does not know any variables created in the main menu view controller.

+4
source share
4 answers

You can add a variable to the class of the second view controller and set this variable to a value depending on which button was pressed during the initialization of the second view controller:

- (IBAction) buttonPressed:(id)button { //Initialize your view controller MyViewController* secondViewController = [[MyViewController alloc] init...]; //Assign a value to a variable you create (I called it pushedButtonValue) so the //viewController knows which button was pressed secondViewController.pushedButtonValue = [button tag]; //Transition to the new view controller [self.navigationController pushViewController:secondViewController animated:YES]; } 
+6
source

An event handler for clicking a button usually has a sender parameter (id). Use this to determine which button was pressed.

 - (IBAction)pushButton:(id)sender { UIButton *button = (UIButton *)sender; } 
+2
source

configure IBOutlets for each button, and then check which sender is which button. But the best way to do this is to have IBActions for each button run, then they can call the method with BOOL or enum, telling about the method, how to behave, or do some other type of processing on their own and call the method that does the general code.

+1
source

Alternatively, you can set a tag for each button, preferably using typedef or enum (for clarity). In the action method, compare the tag value. You may need to attach the sender object to UIButton first.

See: How to set a UIButton tag using NSString?

0
source

All Articles