Search code examples
iosxcode-storyboard

ios storyboard logic


Let's say I have three views on my storyboard.

  • View 1 contains an input field and a button.
  • the input field is where the user puts their answer for "2 + 2"
  • View 2 contains a message of "move on to the first grade!"
  • View 3 contains a message of "you are terrible at math.."

I want to link View 1 and View 2 using the storyboard, but I want to run logic when the button is touched on View 1.

If the input field is == 4 then you are taken to View 2 and if not then you are taken to View 3. Is something like this possible with storyboarding?


Solution

  • Yes

    In storyboard create a segue from View 1 to View 2 by control-dragging from view controller 1 to view controller 2. Click on the segue and give it and identifier (view2 for example). Do the same thing to create a segue from View 1 to View 3 (give it and identifier view3).

    Then in your view1 view controller code add the following code when the in the IBAction method for the button:

    if (input == 4) {
        [self performSegueWithIdentifier: @"view2" sender: self];
    } else {
        [self performSegueWithIdentifier: @"view3" sender: self];
    }
    

    In addition you can a prepareForSegue method to the view1 view controller where you can set properties on the destination view controllers:

    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    {
        if ([[segue identifier] isEqualToString:@"view2"]) 
        {
            [[segue destinationViewController] setManagedObjectContext:self.managedObjectContext];
            [[segue destinationViewController] setSelectedClient:selectedClient];
            [[segue destinationViewController] setAddNoteViewControllerDelegate:self];
        }
        if ([[segue identifier] isEqualToString:@"view3"]) 
        {
            // set properties for view3 view controller
        }
    }