Question

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.

Was it helpful?

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
}

OTHER TIPS

  1. Create a private property on ViewControllerA (perhaps using an enum) to make note of which level is selected.
  2. In your - (IBAction)buttonPressed:(UIButton *)sender method, you need to figure out which button was pressed, and use that information to set the property. Then call [self performSegueWithIdentifier:@"nameOfStoryboardSegue" sender:self];
  3. Create a public property on ViewControllerB to keep track of which level is selected.
  4. Override the prepareForSegue:segue sender:sender method. Instantiate the destination view controller as a ViewControllerB, and set the property on B to match the selected property from A.
  5. Perform the segue.

This question & answer will help you with passing the data between views in the prepareForSegue method, and this question & answers might help with handling all the buttons in the single IBAction method.

I know this is an old question, but I found a simple solution...

duplicate the View Controller from your storyboard and assign the same class to it in identity inspector. You will have a duplicate "storyboard view controller" connected to the same code. With its own icon, tag and storyboard ID

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top