iOS 获取控制器 发表于 2019-02-15 | 分类于 iOS | | 阅读次数: 在一个单例中控制页面跳转的时候,NSObject无法获取控制器,怎么解决呢?这里总结几种获取控制器的方法 在View中获取UIViewController12345678910111213- (UIViewController*)viewController { UIResponder *nextResponder = self; do { nextResponder = [nextResponder nextResponder]; if ([nextResponder isKindOfClass:[UIViewController class]]) return (UIViewController*)nextResponder; } while (nextResponder != nil); return nil;} UINavigationController获取顶部ViewController1self.navigationController.visibleViewController 获取当前展示顶层ViewController12345678910111213141516171819+ (UIViewController *)topViewController { UIViewController *resultVC; resultVC = [self _topViewController:[[UIApplication sharedApplication].keyWindow rootViewController]]; while (resultVC.presentedViewController) { resultVC = [self _topViewController:resultVC.presentedViewController]; } return resultVC;}+ (UIViewController *)_topViewController:(UIViewController *)vc { if ([vc isKindOfClass:[UINavigationController class]]) { return [self _topViewController:[(UINavigationController *)vc topViewController]]; } else if ([vc isKindOfClass:[UITabBarController class]]) { return [self _topViewController:[(UITabBarController *)vc selectedViewController]]; } else { return vc; } return nil;} 获取当前ViewController的UINavigationController123456789101112131415+ (UINavigationController *)nextNavigationController { UIResponder *nextResponder = [self topViewController]; do { nextResponder = [nextResponder nextResponder]; if ([nextResponder isKindOfClass:[UINavigationController class]]) return (UINavigationController*)nextResponder; } while (nextResponder != nil); UITabBarController *rootVC = (UITabBarController *)[[UIApplication sharedApplication].delegate window].rootViewController; return rootVC.selectedViewController;}