第一种方法:写在全局使用的工具类里面
+ (Commons *)sharedCommon;
/*
* 获取当前显示界面
*/
- (UIViewController *)currentViewController;
+(Commons *)sharedCommon {
static Commons *common;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
common = [[Commons alloc] init];
});
return common;
}
/*
* 获取当前显示界面
*/
- (UIViewController *)currentViewController{
UIViewController *resultVC;
AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
resultVC = [self _topViewController:appdelegate.window.rootViewController];
while (resultVC.presentedViewController) {
if ([resultVC.presentedViewController isKindOfClass:[UIAlertController class]]) {
return resultVC;
}
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;
}
第二种方法:写在UIView的扩展里面,这种方式适合在view
里面进行push跳转。如:cell,自定义view。
//获取视图所对应的控制器 -- 下一个相应者
- (UIViewController *)viewController;
//获取视图所对应的控制器 -- 下一个相应者
- (UIViewController *)viewController
{
UIResponder *next = [self nextResponder];
do {
if ([next isKindOfClass:[UIViewController class]]) {
return (UIViewController *)next;
} else {
next = [next nextResponder];
}
} while (next != nil);
return nil;
}
慢慢来,一步一个巴掌印~~~
网友评论