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