Dismiss or remove previous modally presented view controller as soon as the next one appear modally

后端 未结 3 681
谎友^
谎友^ 2021-01-05 06:22

My target include a lot view need to present different view modally base on each user action. Here what I want to do to get cleaner view hierarchy and better user experience

3条回答
  •  悲哀的现实
    2021-01-05 06:30

    Here is my opinion in different perspective,

    1. Root View Controller present Second View Controller
    2. Add FirstView onto Second View
    3. Dismiss FirstView Controller when button pressed.

    Second View Controller,

    class ViewController: UIViewController, FirstViewControllerProtocol {
    
        weak var firstViewController: FirstViewController?
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            print("Not initiated: \(firstViewController)")
    
            firstViewController  = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "FirstViewController") as? FirstViewController
            addChildViewController(firstVC!)
            firstViewController?.delegate = self
            view.addSubview((firstViewController?.view)!)
    
            print("Initiated: \(firstViewController)")
        }
    
        func dismiss() {
            firstViewController?.view.removeFromSuperview()
            firstViewController?.removeFromParentViewController()
    
        }
    }
    

    FirstViewController,

    protocol FirstViewControllerProtocol {
        // Use protocol/delegate to communicate within two view controllers
        func dismiss() 
    }
    
    class FirstViewController: UIViewController {
    
        var delegate: FirstViewControllerProtocol?
    
        override func viewDidLoad() {
            super.viewDidLoad()
        }
    
        @IBAction func dismiss(_ sender: Any) {
            delegate?.dismiss()
        }
    
        deinit {
            print("BYE")
        }
    
    }
    

提交回复
热议问题