Skip to content

Instantly share code, notes, and snippets.

@BeauNouvelle
Last active April 11, 2019 02:46
Show Gist options
  • Save BeauNouvelle/442718f778db4edf52f9b688308be081 to your computer and use it in GitHub Desktop.
Save BeauNouvelle/442718f778db4edf52f9b688308be081 to your computer and use it in GitHub Desktop.
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)
}
}
}
@ksm
Copy link

ksm commented Nov 29, 2018

Thank you for your blog post @BeauNouvelle! I forked and slightly modernized your code (to match my tastes). https://gist.github.com/ksm/1e662f84e073cd227c31f80699d0c197

@BeauNouvelle
Copy link
Author

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