Search code examples
iosobjective-cuinavigationcontrollerdelegatesuistoryboardsegue

How to assign self to another class object, while navigating to another view controller with out segue


I am using below code to navigate to another view controller, i want to assign this self to a delegate of another class, how do i do it ?

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

UINavigationController *controller = [storyboard instantiateViewControllerWithIdentifier:@"storyBoardID"];

self.navigationController presentViewController:controller animated:YES completion:nil];

Solution

  • Get your view Controller from Navigation Controller

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    
    UINavigationController *controller = [storyboard instantiateViewControllerWithIdentifier:@"navigationControllerID"];
    
    TargetVC *targetVC = (TargetVC *)controller.viewControllers.firstObject
       //OR
    TargetVC *targetVC = (TargetVC *)controller.topViewController;
    
    targetVC.mydelegate = self;
    
    [self.navigationController presentViewController:controller animated:YES completion:nil];
    

    Get your view Controller from TabBar Controller

       UITabBarController *homeTabBar=[[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"homeTabBarID"];
    
       TargetVC *targetVC =nil;
    
       UINavigationController *nav = [homeTabBar.viewControllers objectAtIndex:0];
    
      //if you have multiple tab then you can give Index as per your ViewController
       targetVC =(TargetVC*)[nav.viewControllers objectAtIndex:0];
    
       targetVC.mydelegate = self;
    
       [self.navigationController presentViewController:homeTabBar animated:YES completion:nil];