How to set the delegate with a storyboard

前端 未结 3 547
被撕碎了的回忆
被撕碎了的回忆 2020-12-05 07:56

I\'ve been debating with this for a while now, hope you can help me.

I\'ve been creating an app using storyboards mostly, I have a point where I popup a modal box to

相关标签:
3条回答
  • 2020-12-05 08:28

    You're right, the destinationViewController will be a UINavigationController in this case. I wrote a category to handle this common situation:

    // category .h file
    @interface UIStoryboardSegue (NavControllerExtensions)
    // Gets destinationViewCotroller. But if that controller 
    // is a NavigationController, returns the nav controller's 
    // top level view controller instead.
    @property (readonly) id topLevelDestinationViewController;
    @end
    
    // category .m file
    @implementation UIStoryboardSegue (NavControllerExtensions)
    - (id)topLevelDestinationViewController
    {
      id dest = self.destinationViewController;
      if ([dest isKindOfClass:[UINavigationController class]]) {
        UINavigationController* nav = dest;
        dest = nav.topViewController;
      }
      return dest;
    }
    @end
    

    So now you can just do this in any of your prepareForSegue methods, and not need to worry about whether there even exists a NavigationController:

    [[segue topLevelDestinationViewController] setDelegate:self]
    // another example:
    MyViewController *vc = segue.topLevelDestinationViewController;
    vc.delegate = self; // etc.
    

    To answer your second question, I couldn't find a way to set the delegate within IB.

    0 讨论(0)
  • 2020-12-05 08:31

    I found a shorter way in my case (same as yours):

    AddDrinkViewController *controller=[[[segue destinationViewController]viewControllers]objectAtIndex:0];
    
    0 讨论(0)
  • 2020-12-05 08:38

    Basically you need to create an
    Instance of UINavigationController and assign destinationViewController to it
    and grab its topView controller

    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    {
        if ([[segue identifier] isEqualToString:@"showAdd"]) {
    
        UINavigationController *navigationController = segue.destinationViewController;
        AddDrinkViewController *addDrinkcontroller = (AddDrinkViewController *)navigationController.topViewController;
    
        addDrinkcontroller.delegate = self;
    
       }
    }
    
    0 讨论(0)
提交回复
热议问题