Universal Go-back Function for iOS Apps

Photo by Warren Wong on Unsplash

During my career as an iOS developer I wrote around 50 apps. Some of them were small and stayed in the stores just for several months, others stayed alive and got regular updates for years. I’m not a designer myself, I get designs from my clients or a third-party designer. And almost all designs I saw included custom back button on most screens.

Using iOS storyboards to develop UIs, I tried to find an easy way for the user to return to a previous screen, some kind of backward segue. I was reading documentation, forums, discussions, but I found out two things:

  1. There was no way to do it.

And it stays this way up to the present day.

GoBack Function

If something is not done, I need to do it myself. And I did it. One small piece of code included into your project and you get an easy way to empower your back button right in the storyboard editor. Here’s the code:

What’s the idea behind this function?

There are two ways to show a new ViewController keeping the current one in stack:

  1. Presenting it modally.

Some apps mix these 2 ways and get rather complicated sequences of View Controllers. This function (I called it goBack to avoid the name back, which can be used for something else) checks if we’re inside NavigationController, and if yes, it checks if there are more than one ViewControllers. If yes, it pops current ViewController using NavigationController. If no, it dismisses the current ViewController (or NavigationController), which was presented modally earlier.

In all possible scenarios it dismisses the current ViewController and shows the previous one. If it’s the first screen, this function will make no effect.


Add the extension (see above) to your project and create a button, which is supposed to return to a previous screen.

Right-click in storyboard editor and drag Touch Up Inside event to UIViewController itself, you’ll see a list of actions, including goBack. Drop it (release right mouse button) and you’re done. Now this button will work.

Note: if you don’t have a right mouse button, you can hold the Ctrl button and hold your left (only) mouse button. If you use touch pad, use two fingers to simulate right click.

Happy coding and see you next time!

Game and software developer with more than 15 years experience. Founder and CEO at Mariposa Studios, freelancer.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store