Last active
July 31, 2018 15:54
-
-
Save avighnash/bfc68cbd0b73d7f17792e51541c12bd1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 { | |
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