Last active
June 2, 2021 00:55
-
-
Save kyungpyoda/1eab30b6cc704a39b5f0b3bd099764da to your computer and use it in GitHub Desktop.
[Swift] iOS ViewController present to top most
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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