Skip to content

Instantly share code, notes, and snippets.

@jackywang135
Created April 20, 2016 11:43
Show Gist options
  • Save jackywang135/d905da3502b17accc7d9c2fba907a73d to your computer and use it in GitHub Desktop.
Save jackywang135/d905da3502b17accc7d9c2fba907a73d to your computer and use it in GitHub Desktop.
Add UIButton targets using closure
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)
}
}
@sadiq81
Copy link

sadiq81 commented Apr 28, 2018

Swift 4.1

//
// Created by Tommy Sadiq Hinrichsen on 28/04/2018.
// Copyright (c) 2018. All rights reserved.
//

import Foundation
import UIKit

typealias UIButtonTargetClosure = (UIButton) -> ()

class ClosureWrapper: NSObject {
    let closure: UIButtonTargetClosure

    init(_ closure: @escaping UIButtonTargetClosure) {
        self.closure = closure
    }
}

extension UIButton {

    fileprivate struct AssociatedKeys {
        static var touchUpInsideClosure = "targetClosure"
    }

    fileprivate var touchUpInsideClosure: UIButtonTargetClosure? {
        get {
            guard let closureWrapper = objc_getAssociatedObject(self, &AssociatedKeys.touchUpInsideClosure) as? ClosureWrapper else { return nil }
            return closureWrapper.closure
        }
        set(newValue) {
            guard let newValue = newValue else { return }
            objc_setAssociatedObject(self, &AssociatedKeys.touchUpInsideClosure, ClosureWrapper(newValue), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }

    func onTouchUpInside(_ closure: @escaping UIButtonTargetClosure) {
        touchUpInsideClosure = closure
        addTarget(self, action: #selector(UIButton.touchUpInsideAction), for: .touchUpInside)
    }

    @objc
    fileprivate func touchUpInsideAction() {
        guard let touchUpInsideClosure = touchUpInsideClosure else { return }
        touchUpInsideClosure(self)
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment