iOS Present modal view controller on startup without flash

前端 未结 9 1170
囚心锁ツ
囚心锁ツ 2020-12-08 00:53

I\'d like to present modally, at first startup, a tutorial wizard to the user.

Is there a way to present a modal UIViewController on application startup

9条回答
  •  我在风中等你
    2020-12-08 01:05

    This problem still exists in iOS 10. My fix was:

    1. in viewWillAppear add the modal VC as a childVC to the rootVC
    2. in the viewDidAppear:
      1. Remove the modalVC as a child of the rootVC
      2. Modally present the childVC without animation

    Code:

    extension UIViewController {
    
        func embed(childViewController: UIViewController) {
            childViewController.willMove(toParentViewController: self)
    
            view.addSubview(childViewController.view)
            childViewController.view.frame = view.bounds
            childViewController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
    
            addChildViewController(childViewController)
        }
    
    
        func unembed(childViewController: UIViewController) {
            assert(childViewController.parent == self)
    
            childViewController.willMove(toParentViewController: nil)
            childViewController.view.removeFromSuperview()
            childViewController.removeFromParentViewController()
        }
    }
    
    
    class ViewController: UIViewController {
    
        let modalViewController = UIViewController()
    
        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
    
            //BUG FIX: We have to embed the VC rather than modally presenting it because:
            // - Modal presentation within viewWillAppear(animated: false) is not allowed
            // - Modal presentation within viewDidAppear(animated: false) is not visually glitchy
            //The VC is presented modally in viewDidAppear:
            if self.shouldPresentModalVC {
                embed(childViewController: modalViewController)
            }
            //...
        }
    
    
        override func viewDidAppear(_ animated: Bool) {
            super.viewDidAppear(animated)
            //BUG FIX: Move the embedded VC to be a modal VC as is expected. See viewWillAppear
            if modalViewController.parent == self {
                unembed(childViewController: modalViewController)
                present(modalViewController, animated: false, completion: nil)
            }
    
            //....
        }
    }
    

提交回复
热议问题