Responder Chain Controller
While reading the iOSDevWeekly recently, I came across a great post from Roland Leth entitled ‘Handling the Next Button’. Although a great approach, I had recently implemented a very different automated solution and thought it might be worth sharing.
In this post, I’m going to cover an implementation that makes use of a ResponderController
for navigating our user interfaces.
Background
In most of our apps handling the Next
button is often an exercise is patience. It can be troublesome if left unconsidered and although a totally solvable problem, finding a nice reusable abstraction can prove difficult.
I’ve recently been working on an app for Thread and we had a need for Next
/Previous
buttons during checkout, sign-in and various other screens. The architecture means that most of our UI is made up of reusable ‘components’ – which unfortunately meant that any 2 text fields likely didn’t know about each other, nor which context they are being presented in.
Architecture
When I built Peek – I was driven by the idea that functionality and features could be composed on top of the existing user interface. so the approach I’m going to cover leans on these same practices.
What if we just scanned the interface automatically and found all the UIResponder
’s we care about and provide a simple API for navigating them?
ResponderController
I’m not going to cover the code in detail since I have provided a Playground and a link to a Gist for those that want to see how it works and try it out themselves.
Basically the controller just takes a view (allowing you to use multiple controllers for sub-forms) which is then ‘scans’ for UIResponder
subclasses that you might care about.
It filters out those that are hidden, disabled, etc…
It then provides API’s for accessing previous
, next
, current
, begin
& resign
.
Where ResponderController really shines though is that it also exposes Objective-C compatible interfaces via IBOutlet
and IBAction
which allows you to even design your “Next Button” navigation without a single line of code.
To see the Interface Builder approach in action, download the Xcode project below.
The IBAction
APIs even allow you to hook up things like buttons on a toolbar:
UIBarButtonItem(title: "Next", style: .plain,
target: responder, action: #selector(ResponderController.next(_:))
Summary
This doesn’t solve all problems, but we found this approach to be much closer to a plug-and-play solution than others we’d implemented before.
If you liked this approach or have another approach, look me up on Twitter or leave a comment below.