ios,swift2020. 3. 12. 13:30

[ios]swift 최상의 rootviewcontroller replace 하는 방법

 

예를 들어 메인에 있다가 로그인 하고 다시 메인으로 돌아 올시 스텍이 쌓일 수 있다..

 

uitransitionview이 계속 쌓이는걸 볼 수 있는데... 

 

편안하게 최상위 rooview를 바꿔주면 초기화 되서 메인으로 돌아 갈 수 있다..

 

 // 최상의 rootview 갱신

UIApplication.shared.keyWindow?.replaceRootViewController(WantController, animated: true, completion: nil)

 

extension UIWindow

{

    func replaceRootViewController(_ replacementController: UIViewController, animated: Bool, completion: (() -> Void)?) {

           let snapshotImageView = UIImageView(image: self.snapshot())

           self.addSubview(snapshotImageView)

 

           let dismissCompletion = { () -> Void in // dismiss all modal view controllers

               self.rootViewController = replacementController

               self.bringSubview(toFront: snapshotImageView)

               if animated {

                   UIView.animate(withDuration: 0.4, animations: { () -> Void in

                       snapshotImageView.alpha = 0

                   }, completion: { (success) -> Void in

                       snapshotImageView.removeFromSuperview()

                       completion?()

                   })

               }

               else {

                   snapshotImageView.removeFromSuperview()

                   completion?()

               }

           }

           if self.rootViewController!.presentedViewController != nil {

               self.rootViewController!.dismiss(animated: false, completion: dismissCompletion)

           }

           else {

               dismissCompletion()

           }

       }

    

    func snapshot() -> UIImage {

        UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale)

        drawHierarchy(in: bounds, afterScreenUpdates: true)

        guard let result = UIGraphicsGetImageFromCurrentImageContext() else { return UIImage.init() }

        UIGraphicsEndImageContext()

        return result

    }

}

 

[참조] https://stackoverflow.com/questions/15774003/changing-root-view-controller-of-a-ios-window

Posted by thdeodls85