-
-
Save leilee/777191a83f1f2f6948c4c1b5b136dfdd to your computer and use it in GitHub Desktop.
#UIKit #UIControl #gesture
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 { | |
@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