iOS - passing Sender (button) name to addSubview

user885483 picture user885483 · Jan 24, 2012 · Viewed 15.5k times · Source

I have a main view with 3 buttons. Clicking on any of the buttons adds a SubView.

The buttons have different titles and are all linked to IBAction "switchView"

The "switchView" code is below.

- (IBAction)switchView:(id)sender{
    secondView *myViewController = [[secondView alloc] initWithNibName:@"secondView" bundle:nil];
    [self.view addSubview:myViewController.view];
}

The "secondView" loads up correctly and everything works well.

The problem is I want to be able to know which button was the Sender.

I don't want to create 3 subviews, one for each button. The code and XIB would be absolutely the same>

The only difference would be a variable that I would like to set up in the second view (viewDidLoad method) depending on who is the Sender (which button was clicked)

Is this possible? Or I would need to create 3 subViews - one for each button?

Your help is greatly appreciated!

Answer

Markus picture Markus · Jan 24, 2012

You can identify different buttons with the tag property. e.g. with your method:

-(IBAction)switchView:(id)sender {
    UIButton *button = (UIButton*)sender;
    if (button.tag == 1) {
        //TODO: Code here...
    } else if (button.tag == 2) {
        //TODO: Code here...
    } else {
        //TODO: Code here...
    }
}

The tag property can be set via the InterfaceBuilder. Hope this helps.