Sebyddd
Sebyddd

Reputation: 4315

Segues not working programmatically

I migrated a project from using XIB's to Storyboard, according to these instructions: https://stackoverflow.com/a/9708723/2604030 It went good. But I can't make the segues work programmatically, and I need to use them this way, because I have 2 buttons that link to the same ViewController, with different types, hope you understand why from this image.

enter image description here There are 2 difficulty mode buttons. The code I use:

`- (IBAction)btnNormalAct:(id)sender {
    LevelController *wc = [[LevelController alloc] initWithNibName:@"LevelController" type:0];
    [self.navigationController pushViewController:wc animated:YES];
}

- (IBAction)btnTimedAct:(id)sender {
    LevelController *wc = [[LevelController alloc] initWithNibName:@"LevelController" type:1];
    [self.navigationController pushViewController:wc animated:YES];
}`

This worked when I used XIB's, and I am sure I linked everything correctly in the storyboard's VCs. The seagues works if I make them from the storyboard. But how can I manage this situation.

ALSO: are those lines good when changing from XIB's to Storyboard? Is that the right way to do this change (the way shown in the link above)?

    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
}

Upvotes: 2

Views: 98

Answers (2)

Wain
Wain

Reputation: 119031

Don't use the button actions. Connect the segues to the buttons and give the segues unique identifiers. Then implement prepareForSegue:sender: in your controller. When the method fires, check the seque identifier and set the appropriate type on the `destinationViewController'.

When using a storyboard you should instantiate your controllers from the storyboard rather than using initWithNibName:bundle:. This is done by giving each view controller a unique identifier and then calling instantiateViewControllerWithIdentifier: (or, for the initial view controller, just instantiateInitialViewController) on the storyboard which you can get from the current controller (or if required with storyboardWithName:bundle:).

Upvotes: 1

Kevin DiTraglia
Kevin DiTraglia

Reputation: 26058

You can use the PrepareForSegue method to set things on the incoming view controller before it is called:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Make sure your segue name in storyboard is the same as this line
    if ([[segue identifier] isEqualToString:@"YOUR_SEGUE_NAME_HERE"])
    {
        // Get reference to the destination view controller
        LevelController *vc = [segue destinationViewController];

        // Pass any objects to the view controller here, like...
        [vc setType:1];
    }
}

Upvotes: 5

Related Questions