Skip to content

Instantly share code, notes, and snippets.

Embed
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)
}
}
}
@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

BeauNouvelle commented Apr 11, 2019

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