寻找上层的ViewController

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
extension UIView {
func findController() -> UIViewController! {
return self.findControllerWithClass(UIViewController.self)
}
func findNavigator() -> UINavigationController! {
return self.findControllerWithClass(UINavigationController.self)
}
func findControllerWithClass<T>(clzz: AnyClass) -> T? {
var responder = self.nextResponder()
while(responder != nil) {
if (responder!.isKindOfClass(clzz)) {
return responder as? T
}
responder = responder?.nextResponder()
}
return nil
}
}

还有一种通过rootviewController 寻找的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//获取当前屏幕显示的viewcontroller
- (UIViewController *)getCurrentVC
{
UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
return currentVC;
}
- (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC
{
UIViewController *currentVC;
if ([rootVC presentedViewController]) {
// 视图是被presented出来的
rootVC = [rootVC presentedViewController];
}
if ([rootVC isKindOfClass:[UITabBarController class]]) {
// 根视图为UITabBarController
currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
} else if ([rootVC isKindOfClass:[UINavigationController class]]){
// 根视图为UINavigationController
currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
} else {
// 根视图为非导航类
currentVC = rootVC;
}
return currentVC;
}
//swift
/// 获取当前显示的VC
func getCurrentVC()->UIViewController{
let rootViewController = (UIApplication.shared.delegate as! AppDelegate).window?.rootViewController
// if rootViewController == nil{return nil}
let currentVC = self.getCurrentVCFrom(rootVC: rootViewController!)
return currentVC
}
fileprivate func getCurrentVCFrom(rootVC:UIViewController)->UIViewController{
//var currentVC:UIViewController!;
var currentVC:UIViewController = rootVC; // 这里先赋值处理,不然会崩溃(特定条件下)
var rootVC2 = rootVC
if rootVC.presentedViewController != nil{
rootVC2 = rootVC2.presentedViewController!
}
if (rootVC2.isKind(of: UITabBarController.classForCoder())){
rootVC2 = self.getCurrentVCFrom(rootVC: (rootVC2 as! UITabBarController).selectedViewController!)
}else if rootVC2.isKind(of: UINavigationController.classForCoder()){
currentVC = self.getCurrentVCFrom(rootVC: (rootVC2 as! UINavigationController).visibleViewController!)
}else{
currentVC = rootVC2
}
return currentVC
}
Author

陈昭

Posted on

2016-08-30

Updated on

2021-12-27

Licensed under

You need to set install_url to use ShareThis. Please set it in _config.yml.
You forgot to set the business or currency_code for Paypal. Please set it in _config.yml.

Kommentare

You forgot to set the shortname for Disqus. Please set it in _config.yml.