Last active
December 3, 2018 21:08
-
-
Save dyrkabes/f5888f7b0ba5e6bac6fdba43db1e18b4 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
/** | |
A small gesture recogniser that does not need any hustle for those who does not like associated objects and other tough stuff. | |
And it doesn't need to be stored somewhere. Works like a regular GR. Though it has some limitations - it's inherited from `UITapGestureRecognizer`. | |
So it knows only how to handle taps. But do we often need all the types there are? Personally me not. | |
Seems handy for me to purify our view controller from those `@objc` one liners and to become a bit more.. reactive? | |
*/ | |
final class BindableGestureRecognizer: UITapGestureRecognizer { | |
private var action: () -> Void | |
init(action: @escaping () -> Void) { | |
self.action = action | |
super.init(target: nil, action: nil) | |
self.addTarget(self, action: #selector(execute)) | |
} | |
@objc private func execute() { | |
action() | |
} | |
} | |
// Usage example | |
let gestureRecognizer = BindableGestureRecognizer { | |
print("It's alive!") | |
} | |
self.view.addGestureRecognizer(gestureRecognizer) | |
// In case some more meaningful lines are presented, don't forget about [weak self]. We don't want to create those undead buddies. | |
let colorGestureRecognizer = BindableGestureRecognizer { [weak self] in | |
self?.view.backgroundColor = .red | |
} | |
self.view.addGestureRecognizer(colorGestureRecognizer) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment