Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS : 2 Buttons both call the same view controller. How do I find which one was clicked?

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

I have 2 buttons on my main menu that both call the same view controller. Depending on which button was clicked the view controller behaves a little differently. I thought I had the fix using NSNotificationCenter, but it won't catch anything the first time into the view controller (because it hasn't been loaded yet). Are there any other ways to do this?


EDIT: There seems to be some confusion, perhaps on my end. The problem is passing the information across multiple view controllers. The buttons in the Main Menu view controller CALL the second view controller, the problem is that second view controller not having any knowledge of any variables created in the Main Menu view controller.

like image 688
ballofpopculture Avatar asked Jan 20 '23 02:01

ballofpopculture


2 Answers

You could add a variable to the class of the second view controller and set that variable to a value depending on which button was pressed when you initialize 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];
}
like image 94
Carter Avatar answered Feb 01 '23 21:02

Carter


The event handler for the button press will usually have an (id)sender parameter. Use this to determine which button was pressed based .

- (IBAction)pushButton:(id)sender {
    UIButton *button = (UIButton *)sender;
}
like image 31
hspain Avatar answered Feb 01 '23 19:02

hspain