Get top most UIViewController

后端 未结 24 2299
别那么骄傲
别那么骄傲 2020-11-22 14:47

I can\'t seem to get the top most UIViewController without access to a UINavigationController. Here is what I have so far:

UIApplic         


        
24条回答
  •  面向向阳花
    2020-11-22 15:45

    presentViewController shows a view controller. It doesn't return a view controller. If you're not using a UINavigationController, you're probably looking for presentedViewController and you'll need to start at the root and iterate down through the presented views.

    if var topController = UIApplication.sharedApplication().keyWindow?.rootViewController {
        while let presentedViewController = topController.presentedViewController {
            topController = presentedViewController
        }
    
        // topController should now be your topmost view controller
    }
    

    For Swift 3+:

    if var topController = UIApplication.shared.keyWindow?.rootViewController {
        while let presentedViewController = topController.presentedViewController {
            topController = presentedViewController
        }
    
        // topController should now be your topmost view controller
    }
    

    For iOS 13+

    let keyWindow = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
    
    if var topController = keyWindow?.rootViewController {
        while let presentedViewController = topController.presentedViewController {
            topController = presentedViewController
        }
    
    // topController should now be your topmost view controller
    }
    

提交回复
热议问题