Universal Go-back Function for iOS Apps
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:
- There was no way to do it.
- Other people also wanted 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:
- Presenting it modally.
- Pushing it to NavigationController.
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.
Usage
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!