如何在iOS上找到最上层的视图控制器 [英] How to find topmost view controller on iOS

查看:200
本文介绍了如何在iOS上找到最上层的视图控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在遇到了两种情况,可以方便地找到最顶层"的视图控制器(负责当前视图的控制器),但还没有找到一种方法.

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 found a way to do it.

基本上的挑战是:假设一个人在不是视图控制器的类中执行 (或视图) [并且没有活动视图的地址] ,并且尚未传递最顶层视图控制器的地址(或导航控制器的地址),是否有可能找到该视图控制器? (如果可以,怎么办?)

Basically the challenge is this: Given that one is executing in a class that is not a view controller (or a view) [and does not have the address of an active view] and has not been passed the address of the topmost view controller (or, say, the address of the navigation controller), is it possible to find that view controller? (And, if so, how?)

否则,是否有可能找到最顶层的视图?

Or, failing that, is it possible to find the topmost view?

推荐答案

我认为您需要接受的答案和@fishstix的组合

I think you need a combination of the accepted answer and @fishstix's

+ (UIViewController*) topMostController
{
    UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;

    while (topController.presentedViewController) {
        topController = topController.presentedViewController;
    }

    return topController;
}

Swift 3.0 +

func topMostController() -> UIViewController? {
    guard let window = UIApplication.shared.keyWindow, let rootViewController = window.rootViewController else {
        return nil
    }

    var topController = rootViewController

    while let newTopController = topController.presentedViewController {
        topController = newTopController
    }

    return topController
}

这篇关于如何在iOS上找到最上层的视图控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆