Skip to content

Instantly share code, notes, and snippets.

@ksm
Forked from BeauNouvelle/UIBarButtonItem Closure 1.swift
Last active September 13, 2019 11:30
Show Gist options
  • Save ksm/1e662f84e073cd227c31f80699d0c197 to your computer and use it in GitHub Desktop.
Save ksm/1e662f84e073cd227c31f80699d0c197 to your computer and use it in GitHub Desktop.
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