Add UIButton targets using closure

Jacky
2016-04-20T11:43:36Z

UIButton+AddTargetClosure.swift

| import UIKit
|
| typealias UIButtonTargetClosure = UIButton -> ()
|
| class ClosureWrapper: NSObject {
| let closure: UIButtonTargetClosure
| init(_ closure: UIButtonTargetClosure) {
| self.closure = closure
| }
| }
|
| extension UIButton {
|
| private struct AssociatedKeys {
| static var targetClosure = "targetClosure"
| }
|
| private var targetClosure: UIButtonTargetClosure? {
| get {
| guard let closureWrapper = objc_getAssociatedObject(self, &AssociatedKeys.targetClosure) as? ClosureWrapper else { return nil }
| return closureWrapper.closure
| }
| set(newValue) {
| guard let newValue = newValue else { return }
| objc_setAssociatedObject(self, &AssociatedKeys.targetClosure, ClosureWrapper(newValue), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
| }
| }
|
| func addTargetClosure(closure: UIButtonTargetClosure) {
| targetClosure = closure
| addTarget(self, action: #selector(UIButton.closureAction), forControlEvents: .TouchUpInside)
| }
|
| func closureAction() {
| guard let targetClosure = targetClosure else { return }
| targetClosure(self)
| }
| }