Skip to content

Instantly share code, notes, and snippets.

@leilee
Forked from avighnash/ClosureSelector.swift
Last active November 24, 2017 04:31
Show Gist options
  • Save leilee/777191a83f1f2f6948c4c1b5b136dfdd to your computer and use it in GitHub Desktop.
Save leilee/777191a83f1f2f6948c4c1b5b136dfdd to your computer and use it in GitHub Desktop.
#UIKit #UIControl #gesture
class ClosureSleeve {
let closure: () -> ()
init(attachTo: AnyObject, closure: @escaping () -> ()) {
self.closure = closure
objc_setAssociatedObject(attachTo, "[\(arc4random())]", self, .OBJC_ASSOCIATION_RETAIN)
}
@objc func invoke() {
closure()
}
}
enum GestureRecognizer {
case pan, tap, pinch, swipe, longPress, screenEdge
}
extension UIView {
@discardableResult
func actionBlock(of type: GestureRecognizer, action: @escaping () -> ()) -> UIGestureRecognizer {
let sleeve = ClosureSleeve(attachTo: self, closure: action)
let gesture: UIGestureRecognizer
switch type {
case .pan:
gesture = UIPanGestureRecognizer(target: sleeve, action: #selector(ClosureSleeve.invoke))
case .tap:
gesture = UITapGestureRecognizer(target: sleeve, action: #selector(ClosureSleeve.invoke))
case .pinch:
gesture = UIPinchGestureRecognizer(target: sleeve, action: #selector(ClosureSleeve.invoke))
case .swipe:
gesture = UISwipeGestureRecognizer(target: sleeve, action: #selector(ClosureSleeve.invoke))
case .longPress:
gesture = UILongPressGestureRecognizer(target: sleeve, action: #selector(ClosureSleeve.invoke))
case .screenEdge:
gesture = UIScreenEdgePanGestureRecognizer(target: sleeve, action: #selector(ClosureSleeve.invoke))
}
addGestureRecognizer(gesture)
return gesture
}
}
extension UIControl {
func actionBlock(event: UIControlEvents, action: @escaping () -> ()) {
let sleeve = ClosureSleeve(attachTo: self, closure: action)
self.addTarget(sleeve, action: #selector(ClosureSleeve.invoke), for: event)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment