How to correctly dismiss a UINavigationController that's presented as a modal?

后端 未结 8 1802
情话喂你
情话喂你 2021-02-01 16:04

In my TabBarViewController, I create a UINavigationController and present it as a modal.

var navController =  UINavigationController()
let messageVC         


        
8条回答
  •  悲哀的现实
    2021-02-01 16:52

    if you want to just present a viewcontroller, then directly you can present that viewcontroller and no need to take a navigation controller for that particular viewcontroller.

    But when we need to navigate from that presented view controller then we need to take a view controller as a root view of navigation controller. So that we can navigate from that presented view controller.

    let messageVC = self.storyboard?.instantiateViewControllerWithIdentifier("MessagesViewController") as! MessagesViewController
    let MynavController = UINavigationController(rootViewController: messageVC)
    self.presentViewController(MynavController, animated: true, completion: nil)
    

    and from that presented view controller, you can push to another view controller and also pop from another view controller.

    And from presented view controller, here messageVC, we have to dismiss that as

    func swipedRightAndUserWantsToDismiss() {
      self.dismiss(animated: true, completion: nil)
    }
    

    which will dismiss messageVC successfully and come back to origin viewcontroller from where we have presented messageVC.

    This is the right flow to perform presentViewController with navigation controller, to continue the navigation between the view controllers.

    And for more if you are not sure that messageVC is presented or pushed, then you can check it by this answer.

    And the swift version to check that is

    func isModal() -> Bool {
        if((self.presentingViewController) != nil) {
            return true
        }
    
        if(self.presentingViewController?.presentedViewController == self) {
            return true
        }
    
        if(self.navigationController?.presentingViewController?.presentedViewController == self.navigationController) {
            return true
        }
    
        if((self.tabBarController?.presentingViewController?.isKindOfClass(UITabBarController)) != nil) {
            return true
        }
    
        return false
    }
    

    So our final action to dismiss is like

    func swipedRightAndUserWantsToDismiss() {
    
                if self.isModal() == true {
                    self.dismiss(animated: true, completion: nil)
                }
                else {
                    self.navigationController?.popViewControllerAnimated(true)
                }
    
            }
    

提交回复
热议问题