Dismiss and Present View Controller in Swift

前端 未结 5 684
生来不讨喜
生来不讨喜 2020-12-09 11:52

Hi I\'m trying to present a viewcontroller and dismiss my current modal view but this code is not working

self.dismissViewControllerAnimated(true, completion         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-09 12:34

    you can't do that because when the UIViewController A calls the UIViewController B and the first controller is dismissed then the two controllers are nil.

    You need to have a UIViewController as a base, in this case MainViewController is the base. You need to use a protocol to call the navigation between controllers.

    you can do using protocol let say for example as bellow:-

    In to your viewController setting Protocol :

        protocol FirstViewControllerProtocol {
        func dismissViewController()
    }
    
    class FirstViewController: UIViewController {
        var delegate:FirstViewControllerProtocol!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // Do any additional setup after loading the view.
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    
    
        @IBAction func goBack(sender: AnyObject) {
            self.dismissViewControllerAnimated(true) { 
                self.delegate!.dismissViewController()
            }
        }
    

    Now in your main view controller

    class MainViewController: UIViewController, FirstViewControllerProtocol {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    @IBAction func goToFirstViewController(sender: AnyObject) {
        let viewController = self.storyboard?.instantiateViewControllerWithIdentifier(String(FirstViewController)) as! FirstViewController
        viewController.delegate = self
        self.presentViewController(viewController, animated: true, completion: nil)
    }
    
    
    
    //MARK: Protocol
    func dismissViewController() {
        if let viewController = self.storyboard?.instantiateViewControllerWithIdentifier(String(SecondViewController)){
            self.presentViewController(viewController, animated: true, completion: nil)
        }
    }
    

    Code example with storyboard:


提交回复
热议问题