Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Slightly improved version of Beau Nouvelle's UIBarButtonItem closure extension. I hid all the helper classes within the extension and made them private, so as not to pollute the global namespace. Original article: https://medium.com/@BeauNouvelle/adding-a-closure-to-uibarbuttonitem-24dfc217fe72
import Foundation
import UIKit
public extension UIBarButtonItem {
public typealias TargetClosure = (UIBarButtonItem) -> ()
public convenience init(title: String?, style: UIBarButtonItem.Style = .plain, closure: @escaping TargetClosure) {
self.init(title: title, style: style, target: nil, action: nil)
targetClosure = closure
action = #selector(UIBarButtonItem.closureAction)
}
private struct AssociatedKeys {
static var targetClosure = "targetClosure"
}
private class ClosureWrapper: NSObject {
let closure: TargetClosure
init(_ closure: @escaping TargetClosure) {
self.closure = closure
}
}
private var targetClosure: TargetClosure? {
get {
guard let closureWrapper = objc_getAssociatedObject(self, &AssociatedKeys.targetClosure) as? ClosureWrapper else {
return nil
}
return closureWrapper.closure
}
set {
guard let newValue = newValue else {
return
}
objc_setAssociatedObject(self, &AssociatedKeys.targetClosure, ClosureWrapper(newValue), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
@objc private func closureAction() {
targetClosure?(self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment