iOS - passing Sender (button) name to addSubview

15,505

Solution 1

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.

Solution 2

I think you can solve in 2 ways:

  1. Create a property like: @property (nonatomic, strong) IBOutlet UIButton *button1, *button2, *button3; in your viewcontroller and link the buttons to them as referencing outlet on the XIB.
  2. Give a different tag to each button on your xib and ask for the tag of the sender with UIButton *b=(UIButton*)sender; b.tag; like Markus posted in detail.
Share:
15,505
user885483
Author by

user885483

Updated on June 04, 2022

Comments

  • user885483
    user885483 almost 2 years

    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!