iOS Storyboard Tips & Tricks
I’ve been spending some time diving into iOS development for reals during my spare time the last couple of months. In this time I’ve come to learn a lot of things about storyboards, other than that they are pretty awesome.
Here are two things in particular.
Table View Data Sources and Delegates
In the very first issue of objc.io they discuss how to make your UITableViewControllers lighter by moving data sources and delegates to separate objects. Turns out you can achieve this with storyboards — without the need to create a custom table view controller subclass!
- In Interface Builder search for
Objectin the Object Library (lower right). - Hit
Returnor drag theObjectto your table view. - If it’s not automatically selected, seletect the
Objectand open up the Identity Inspector. - In the section
Custom Classenter the name of your custom data source class. - Control drag from the table view to your data source object, select
data sourcefrom the popup menu. - You’re done!
By hooking things up this way I’ve come along way without creating a ton of custom controllers just to create my data sources.
The Exit/Unwind Segue
You probably know this already if you’ve ever done anything with storyboards, but it was news to me.
- Implement a method in a view controller (any view controller — I think) with the following signature
func myUnwindSegue(segue: UIStoryboardSegue). - Control drag from any button to the
Exiticon on your current view and select the method you want to “unwind” to.
Whenever your button is tapped the current view controller will be dimissed if it was presented modally or popped from the navigation stack if it’s contained in a navigation controller. Basically it’ll do the right thing to go back to the view controller implementing the method. If the destination view controller cannot be unwound to, because it’s not in the navigation stack or something, the button will do nothing (I think).
Now, any function with the above signature will show up in the list of available ones. So first of all, if you have lots of view controllers you want to unwind to you probably want to name your methods in a unique way, and not just back. Maybe returnToListOfThings or saveThisThing.