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

查看:23
本文介绍了如何在 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天全站免登陆