How to find topmost view controller on iOS

后端 未结 30 2320
遥遥无期
遥遥无期 2020-11-22 08:40

I\'ve run into a couple of cases now where it would be convenient to be able to find the \"topmost\" view controller (the one responsible for the current view), but haven\'t

30条回答
  •  情深已故
    2020-11-22 09:08

    Another solution relies on the responder chain, which may or may not work depending on what the first responder is:

    1. Get the first responder.
    2. Get the UIViewController associated with that first responder.

    Example pseudo code:

    + (UIViewController *)currentViewController {
        UIView *firstResponder = [self firstResponder]; // from the first link above, but not guaranteed to return a UIView, so this should be handled more appropriately.
        UIViewController *viewController = [firstResponder viewController]; // from the second link above
        return viewController;
    }
    

提交回复
热议问题