Skip to content

Instantly share code, notes, and snippets.

Last active April 11, 2019 02:46
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
UIBarButtonItem Closure
extension UIBarButtonItem {
/// Typealias for UIBarButtonItem closure.
private typealias UIBarButtonItemTargetClosure = (UIBarButtonItem) -> ()
private class UIBarButtonItemClosureWrapper: NSObject {
let closure: UIBarButtonItemTargetClosure
init(_ closure: @escaping UIBarButtonItemTargetClosure) {
self.closure = closure
private struct AssociatedKeys {
static var targetClosure = "targetClosure"
private var targetClosure: UIBarButtonItemTargetClosure? {
get {
guard let closureWrapper = objc_getAssociatedObject(self, &AssociatedKeys.targetClosure) as? UIBarButtonItemClosureWrapper else { return nil }
return closureWrapper.closure
set(newValue) {
guard let newValue = newValue else { return }
objc_setAssociatedObject(self, &AssociatedKeys.targetClosure, UIBarButtonItemClosureWrapper(newValue), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
Copy link

Awesome! Glad it was useful.
Your version is much better!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment