Adding a closure to UIBarButtonItem
If you’re looking for an updated version of this article that covers Swift 5 and UIControls (such as UIButton), you can find it on my dedicated Blog: https://getswifty.dev/adding-closures-to-buttons-in-swift/
So one of the things I still find a little backward and unnatural to use in Swift is the Target-Action pattern.
Apple eventually gave us #selector to add things like type safety and code completion, but that hardly feels like a real solution. It certainly doesn’t feel Swifty…
Closures are Swifty. So let’s add some of those!
We’ll start by setting up our wrapper class and begin filling out our extension with some boilerplate. This will help us get around the stored property restrictions we currently have with extensions in Swift.
UIBarButtonItem has an initializer that accepts a target and action as parameters, which is a bit different to how UIButton adds a target-action.
So what we’re going to do is create a new convenience initialiser which will make use of the initialiser already available to us.
Add the following code to the bottom of the extension.
We start off by calling self.init apply our title and style, but leave target-action empty. Afterwards we store a reference to the passed in closure into our targetClosure we created earlier.
Then finally the action property on UIBarButtonItem is set to a selector, which will run the closure stored in targetClosure anytime the action is triggered, such as tapping on the button.
It’s a lot of extra code but it enables us to write less code elsewhere in our applications, and increasing readability. The same principles we use here can be used for many other UIKit components.
This is how you can now set up your UIBarButtonItem.
I feel like that looks much better and far more useful. You can now call multiple functions within the closure. You get a reference to your button object, and also access to other code within the same scope.
As an extra bonus, when it comes to UIButtons I like to add separate closures depending on how the user interacts with them (e.g. touchUpInside).
So much cleaner!
I have my first book out called Simulations In Swift! Learn how you can use Swift playgrounds to create powerful simulations and generate digital artwork.
You can get it here: http://a.co/4Xu0sxz
I’m also available for hire!