apple/iOS, UIKit, Documentation
iOS 최상단 ViewController + UIWindow (keywindow)
lgvv
2022. 3. 15. 23:33
iOS 최상단 ViewController + UIWindow (keywindow)
최상단에 위치한 ViewContoller를 재귀를 이용해 안전하게 찾기
최상단 ViewController를 찾는 코드
각 컨트롤러의 객체 타입에 맞게 재귀를 이용해 최상단 뷰 컨트롤러를 찾는 코드
public extension UIViewController {
func topMostViewController() -> UIViewController {
if let presentedViewController = self.presentedViewController {
return presentedViewController.topMostViewController()
}
if let navigationController = self as? UINavigationController {
return navigationController.visibleViewController?.topMostViewController() ?? navigationController
}
if let tabBarController = self as? UITabBarController {
return tabBarController.selectedViewController?.topMostViewController() ?? tabBarController
}
return self
}
}
UIwindow Keywindow Extension
최상단 뷰를 찾았다면 해당 코드와 궁합이 좋음
public extension UIWindow {
static var keyWindow: UIWindow? {
UIApplication.shared.connectedScenes
.compactMap({ $0 as? UIWindowScene })
.flatMap({ $0.windows })
.first(where: { $0.isKeyWindow })
}
}
Usage
알림이나 공유하기 기능 등에 사용할 수 있음
func show(_ activityViewController: UIActivityViewController) {
if let keyWindow = UIWindow.keyWindow {
let topViewController = keyWindow.rootViewController?.topMostViewController()
topViewController?.present(activityViewController, animated: true, completion: nil)
}
}