iOS how to simple return back to previous presented/pushed view controller programmatically?

前端 未结 2 680
萌比男神i
萌比男神i 2021-02-05 14:42

How to return back to previous view controller programmatically? I found this answer, but there is an example that demonstrate how to go back if we have navigation stack:

<
2条回答
  •  面向向阳花
    2021-02-05 15:35

    You can easily extend functionality of any inbuilt classes or any other classes through extensions. This is the perfect use cases of extensions in swift.

    You can make extension of UIViewController like this and use the performSegueToReturnBack function in any UIViewController

    Swift 2.0

    extension UIViewController {
        func performSegueToReturnBack()  {
            if let nav = self.navigationController {
                nav.popViewControllerAnimated(true)
            } else {
                self.dismissViewControllerAnimated(true, completion: nil)
            }
        }
    }
    

    Swift 3.0

    extension UIViewController {
        func performSegueToReturnBack()  {
            if let nav = self.navigationController {
                nav.popViewController(animated: true)
            } else {
                self.dismiss(animated: true, completion: nil)
            }
        }
    }
    

    Note:

    Someone suggested that we should assign _ = nav.popViewControllerAnimated(true) to an unnamed variable as compiler complains if we use it without assigning to anything. But I didn't find it so.

提交回复
热议问题