Skip to content

Instantly share code, notes, and snippets.

@kyungpyoda
Last active June 2, 2021 00:55
Show Gist options
  • Save kyungpyoda/1eab30b6cc704a39b5f0b3bd099764da to your computer and use it in GitHub Desktop.
Save kyungpyoda/1eab30b6cc704a39b5f0b3bd099764da to your computer and use it in GitHub Desktop.
[Swift] iOS ViewController present to top most
//
// UIViewController+presentToTop.swift
//
// Created by 홍경표 on 2021/06/01.
//
import UIKit
extension UIViewController {
func presentToTop() {
let currentTop = UIApplication.shared.keyWindowCurrentScene?.topViewController
currentTop?.present(self, animated: true, completion: nil)
}
}
extension UIWindow {
var topViewController: UIViewController? {
var top = self.rootViewController
while true {
if let presented = top?.presentedViewController {
top = presented
} else if let nav = top as? UINavigationController {
top = nav.visibleViewController
} else if let tab = top as? UITabBarController {
top = tab.selectedViewController
} else {
break
}
}
return top
}
}
extension UIApplication {
class var keyWindowOfCurrentScene: UIWindow? {
shared.windows.first(where: { $0.isKeyWindow })
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment