Search code examples
iosxcodeuibuttonuistoryboardsegueibaction

Multiple buttons segue to the same view controller with unique identifier


I have a ViewControllerA that has roughly 15 buttons in my case they represent levels, When a level is pressed it segues to ViewControllerB. Now it doesn't make sense to manually ctrl+drag and create segue for each button. I'm wondering how can a button segue to ViewControllerB and have a unique identifier then ill be passing an object in other words data to ViewControllerB to recognize which level the user pressed. I also want to point out that I have a push view controller. So far one of my unsuccessful attempts were to do is to ctrl+drag all the buttons and create a method called:(the button title in my case is the level number)

- (IBAction)buttonPressed:(UIButton *)sender {
    [self performSegueWithIdentifier:[sender currentTitle] sender:self];  
}

afterwards I call the prepareForSegue:segue sender:sender method.To be honest Im new to iOS developing. Any helpful tutorial or article would be great for me. Thanks in advance for all helpers.


Solution

  • You were close with your unsuccessful attempt. You only want one identifier for a single segue that you set up in IB directly from the controller to VCB. In your action method, that all the button's invoke, do this (notice that I'm passing the button in the sender argument):

    - (IBAction)buttonPressed:(UIButton *)sender {
        [self performSegueWithIdentifier:@"MySegueIdentifier" sender:sender];  
    }
    

    Then in prepareForSegue, you can use the sender argument to get the button's title:

    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(UIButton *)sender {
            NSString *title = sender.currentTitle;
            // do what you need with the title
    }