Search code examples
objective-cuiviewcontrolleruinavigationcontrolleruibuttonpushviewcontroller

Push view to navigation controller from button in other class


I have a UIButton that I create in my sub class ViewController, and add it to my MainViewController.

Now, I added a target method to this button that should push another view controller to my Navigation controller (the one that in the MainViewController).

I know that the method did call when I push the button, but the view wasn't push to the Navigation Controller.

I scanned this drawing - this is the drawing (I also added part of my code):

question Drawing

This is the code I'm using in my button: (remember it's in a deferent ViewController).

- (void)buttonPressed:(UIButton *)sender
{
    Photo_ScreenGlobalView *photo = [[Photo_ScreenGlobalView alloc] init];
    [self.navigationController pushViewController:photo animated:YES];
}

Solution

  • Usually I solve these situations with delegation. If there is a view controller which is subordinate to another (i.e. a "sub" view controller) but should have the ability to trigger navigation changes, etc... then it should have a weak pointer back to it's 'parent'. Then the parent VC should implement an appropriately named protocol with a callback for the child to use. The names of these things can be generic, such as @property navigationDelegate and requestNavigationToViewController: or they can be more semantic, such as @property userFormDelegate and userFormDoneButtonPressed:

    Generally speaking, a subordinate view controller should not be able to directly modify navigation at it's parent's level; but it can trigger it via more loosely-coupoled interfaces like these.