최상위 view controller를 찾는 방법에 대한 고민

태그: 

1 답변 글타래를 보이고 있습니다
  • 글쓴이
    • 종호
      참가자
      • 글작성 : 9
      • 답글작성 : 2

      커스텀하여 만든 UIView 나 UIViewController 클래스에서 자신을 호출한 부모 view controller 찾을때 또는 UIAlertController를 UIViewController에서 바로 사용하지 않는 경우에 최상위 view controller를 찾을때 어떤 방식이 가장 좋은 방식인지에 대한 고민이 있습니다.

      커스텀하여 만든 UIView 나 UIViewController에서는 호출하는 함수 인자에 해당 view controller를 넘겨주는 방식을 쓰거나 UIAlertController의 경우
      최상위 view controller를 찾는 공통 함수를 작성하여 present 하고 있는데 (참고: https://taesulee.tistory.com/2) 해당 함수에서 사용되는 keywindow는 apple 공식 문서에서 확인했을때 deprecated 되는것 같아 (https://developer.apple.com/documentation/uikit/uiapplication) 공통 함수를 다시 작성해야 할지 아니면 해당 경우에서 사용되는 다른 좋은 방식이 있는지 궁금합니다!

      감사합니다~

    • 멍단비
      참가자
      • 글작성 : 10
      • 답글작성 : 98

      도움이 될지 모르겠습니다만,, 일단 keywindow deprecated 된 것 같은 경우는 저는 요렇게 씁니다.

      UIApplication.shared.windows.filter {$0.isKeyWindow}.first
      

      출처: https://stackoverflow.com/questions/57134259/how-to-resolve-keywindow-was-deprecated-in-ios-13-0

      그리고 최상단 뷰컨트롤러를 불러오는 경우 같은 것은 아마 더 좋은 방법이 있을건데요.
      저는 급한대로 이렇게 일단 만들어서 쓰고 있어요.

      extension UIApplication {
      
      func currentTopViewController(controller: UIViewController? = UIApplication.shared.connectedScenes.compactMap{$0 as? UIWindowScene}.first?.windows.filter{$0.isKeyWindow}.first?.rootViewController) -> UIViewController? {
      
      if let navigationController = controller as? UINavigationController {
             return currentTopViewController(controller: navigationController.visibleViewController)
         }
         if let tabbarController = controller as? UITabBarController {
             if let selected = tabbarController.selectedViewController {
                 return currentTopViewController(controller: selected)
             }
         }
         if let presented = controller?.presentedViewController {
             return currentTopViewController(controller: presented)
         }
         return controller
      
      }
      
      }
      
      • 이 답변은 멍단비에 의해 4 years, 1 month 전에 수정됐습니다.
      • 이 답변은 멍단비에 의해 4 years, 1 month 전에 수정됐습니다.
      • 이 답변은 멍단비에 의해 4 years, 1 month 전에 수정됐습니다.
      • 이 답변은 멍단비에 의해 4 years, 1 month 전에 수정됐습니다.
1 답변 글타래를 보이고 있습니다
  • 답변은 로그인 후 가능합니다.

logo landscape small

사업자번호 : 743-81-02195
통신판매업 신고번호 : 제 2022-충북청주-1278 호
고객센터 : 카카오톡채널 @yagom