一、根据view得到当前viewController
第1种方法:
- (UIViewController *)findSuperViewController:(UIView *)view
{
UIResponder *responder = view;
// 循环获取下一个响应者,直到响应者是一个UIViewController类的一个对象为止,然后返回该对象.
while ((responder = [responder nextResponder])) {
if ([responder isKindOfClass:[UIViewController class]]) {
return (UIViewController *)responder;
}
}
return nil;
}
第2种方法:
- (UIViewController *)getCurrentViewControllerByView:(UIView *)view
{
UIResponder *next = [view nextResponder];
do {
if ([next isKindOfClass:[UIViewController class]]) {
return (UIViewController *)next;
}
next = [next nextResponder];
} while (next != nil);
return nil;
}
二、获取到当前控制器viewController的方法
第1种方法:
- (UIViewController *)findCurrentViewController
{
UIWindow *window = [[UIApplication sharedApplication].delegate window];
UIViewController *topViewController = [window rootViewController];
while (true) {
if (topViewController.presentedViewController) {
topViewController = topViewController.presentedViewController;
} else if ([topViewController isKindOfClass:[UINavigationController class]] && [(UINavigationController*)topViewController topViewController]) {
topViewController = [(UINavigationController *)topViewController topViewController];
} else if ([topViewController isKindOfClass:[UITabBarController class]]) {
UITabBarController *tab = (UITabBarController *)topViewController;
topViewController = tab.selectedViewController;
} else {
break;
}
}
return topViewController;
}
第2种方法:
- (UIViewController *)getCurrentViewController
{
UIViewController *result = nil;
// 获取默认的window
UIWindow * window = [[UIApplication sharedApplication] keyWindow];
// app默认windowLevel是UIWindowLevelNormal,如果不是,找到它。
if (window.windowLevel != UIWindowLevelNormal) {
NSArray *windows = [[UIApplication sharedApplication] windows];
for(UIWindow * tmpWin in windows) {
if (tmpWin.windowLevel == UIWindowLevelNormal) {
window = tmpWin;
break;
}
}
}
// 获取window的rootViewController
result = window.rootViewController;
while (result.presentedViewController) {
result = result.presentedViewController;
}
if ([result isKindOfClass:[UITabBarController class]]) {
result = [(UITabBarController *)result selectedViewController];
}
if ([result isKindOfClass:[UINavigationController class]]) {
result = [(UINavigationController *)result visibleViewController];
}
return result;
}
网友评论