第一种
public extension UIWindow {
public func topMostWindowController()->UIViewController? {
var topController = rootViewController
while let presentedController = topController?.presentedViewController {
topController = presentedController
}
return topController
}
public func currentViewController()->UIViewController? {
var currentViewController = topMostWindowController()
if currentViewController is UITabBarController{
currentViewController = (currentViewController as! UITabBarController).selectedViewController
}
while currentViewController != nil && currentViewController is UINavigationController && (currentViewController as! UINavigationController).topViewController != nil {
currentViewController = (currentViewController as! UINavigationController).topViewController
}
return currentViewController
}
}
调用:
let kAppDelegate = UIApplication.shared.delegate as! AppDelegate
var kWindow = kAppDelegate.window
kWindow?.currentViewController()?.present(alertVC, animated: true, completion: nil)
第二种,UIViewController
let kAppDelegate = UIApplication.shared.delegate as! AppDelegate
var kWindow = kAppDelegate.window
var currentViewController: UIViewController?{
let firstView = kWindow?.subviews.first
let secondView = firstView?.subviews.first
guard let vc = secondView?.parentController else {
kWindow?.makeKeyAndVisible()
return (kWindow?.rootViewController as? UINavigationController)?.visibleViewController
}
if vc.isKind(of: UITabBarController.self) {
let tab = vc as! UITabBarController
guard tab.selectedViewController!.isKind(of: UINavigationController.self) else {
return tab.selectedViewController
}
let nav = tab.selectedViewController as! UINavigationController
return nav.viewControllers.last
}
else if vc.isKind(of: UINavigationController.self) {
let nav = vc as! UINavigationController
return nav.viewControllers.last
}
else {
return vc
}
}
extension UIView {
var parentController: UIViewController?
{
var responder = self.next
while (responder != nil) {
if responder!.isKind(of: UIViewController.self) {
return responder as? UIViewController
}
responder = responder!.next
}
return nil
}
}
网友评论