Call a parent view controller (through a navigationcontroller)

后端 未结 3 1553
傲寒
傲寒 2020-11-27 04:50

Currently I add a viewcontroller using pushViewController:animated: and now from within that new one would like to call a method inside my \"parent\"-controller

3条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 05:38

    self.navigationController.viewControllers
    

    Returns an array of all the view controllers in the navigation stack. The current view controller is at the top of the stack, the previous view controller is the next one down, and so forth.

    So, you can do the following:

    NSArray *viewControllers =     self.navigationController.viewControllers;
    int count = [viewControllers count];
    id previousController = [viewControllers objectAtIndex:count - 2];
    if ([previousController respondsToSelector:@selector(myMethod)])
        [previousController myMethod];
    

    If you know what class the previous controller is you can cast it explicity instead of using id.

提交回复
热议问题