简体   繁体   中英

How to dismiss a view controller in a navigation controller, without dismissing the whole stack

Basically I have tab bar controller with two tabs, each holds a separate navigation controller, each with a couple of views (see below).

在此处输入图片说明

In the "top" navigation controller (held in the right tab), I can choose an image, and then am taken to the rightmost screen to preview the image...

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let image = info[UIImagePickerControllerEditedImage] as? UIImage {

        let previewController = self.storyboard?.instantiateViewController(withIdentifier: "previewVC") as! PreviewViewController
        previewController.img = image
        previewController.navigationItem.setHidesBackButton(true, animated: false)
        self.navigationController?.pushViewController(previewController, animated: true)

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

...where I tap "post". This uploads the image and calls self.tabBarController?.selectedIndex = 0

That simply takes me to the image feed, which is in the "bottom" navigation controller (left tab). So far so good. However, the preview screen is still displayed in the "right" tab, when I need the upload screen to be displayed after I post.

If I call self.dismiss(animated: true, completion: nil) when I tap post, the entire navigation controller is dismissed and I'm taken back to the login screen.

So I'm trying to dismiss the preview controller so the upload controller is shown as the default view in the right tab, without dismissing the entire stack in that navigation controller.

How can I do this?

If you use navigation controllers to add view controllers to the navigation stack (push), you can remove them by calling a pop function. When you present view controllers modally, you call dismiss to remove the view controller.

The delegate function gives you the (image picker) view controller and you should dismiss that, not the view controller that is the delegate (usually the presenting view controller). Maybe try something like this:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let image = info[UIImagePickerControllerEditedImage] as? UIImage {

        let previewController = self.storyboard?.instantiateViewController(withIdentifier: "previewVC") as! PreviewViewController
        previewController.img = image
        previewController.navigationItem.setHidesBackButton(true, animated: false)
        self.navigationController?.pushViewController(previewController, animated: true)

        picker.dismiss(animated: true, completion: nil)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM