Skip to content

Instantly share code, notes, and snippets.

@rehannali
Created November 7, 2022 06:59
Show Gist options
  • Save rehannali/7ad9f419e1acfc10bc217aa9bca30925 to your computer and use it in GitHub Desktop.
Save rehannali/7ad9f419e1acfc10bc217aa9bca30925 to your computer and use it in GitHub Desktop.
Find Top View Controller
public extension NSObject {
func findTopViewController(vc: UIViewController) -> UIViewController {
if (vc.presentedViewController != nil) {
return UIViewController().findTopViewController(vc:vc.presentedViewController!)
} else if (vc.isKind(of: AKSideMenu.self)) {
let rvc = vc as! AKSideMenu
if let left = rvc.leftMenuViewController {
return UIViewController().findBestVC(vc: left)
}else if let right = rvc.rightMenuViewController {
return UIViewController().findBestVC(vc: right)
}
return UIViewController().findTopViewController(vc:rvc)
} else if (vc.isKind(of: UINavigationController.self)) {
let rvc = vc as! UINavigationController
if rvc.viewControllers.count > 0 {
return UIViewController().findTopViewController(vc:rvc.topViewController!)
}
return vc
} else if (vc.isKind(of: UITabBarController.self)) {
let rvc = vc as! UITabBarController
if rvc.viewControllers!.count > 0 {
return UIViewController().findTopViewController(vc:rvc.selectedViewController!)
}
return vc
} else {
return vc
}
}
class func currentTopViewController() -> UIViewController {
let vc = UIApplication.keyWindow!.rootViewController
return UIViewController().findTopViewController(vc: vc!)
}
}
public extension UIViewController {
func currentVC() -> UIViewController {
let vc = UIApplication.keyWindow!.rootViewController
return findBestVC(vc: vc!)
}
func findBestVC(vc: UIViewController) -> UIViewController {
if (vc.presentedViewController != nil) {
return UIViewController().findBestVC(vc:vc.presentedViewController!)
} else if (vc.isKind(of: AKSideMenu.self)) {
let rvc = vc as! AKSideMenu
if let left = rvc.leftMenuViewController {
return UIViewController().findBestVC(vc: left)
}else if let right = rvc.rightMenuViewController {
return UIViewController().findBestVC(vc: right)
}
return UIViewController().findBestVC(vc:rvc)
} else if (vc.isKind(of: UINavigationController.self)) {
let rvc = vc as! UINavigationController
if rvc.viewControllers.count > 0 {
return UIViewController().findBestVC(vc:rvc.topViewController!)
}
return vc
} else if (vc.isKind(of: UITabBarController.self)) {
let rvc = vc as! UITabBarController
if rvc.viewControllers!.count > 0 {
return UIViewController().findBestVC(vc:rvc.selectedViewController!)
}
return vc
} else {
return vc
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment