I was wondering, whether it is possible to initialize a UIGestureRecognizer
with a block, instead of having to create a separate function for it.
In Swift 3, I believe, this was introduced for timers.
I've implemented something similar to the code posted here since it didn't work for me.
This is my code:
class TapGestureRecognizer: UITapGestureRecognizer {
private var closure: (() -> ())?
init() {
super.init(target: TapGestureRecognizer.self, action: #selector(self.runAction))
}
convenience init(for view: UIView, block: @escaping (() -> Void)) {
self.init()
closure = block
view.addGestureRecognizer(self)
}
func runAction() {
print("executed")
if closure == nil { return }
closure!()
}
}
When I create a TapGestureRecognizer
like this:
TapGestureRecognizer(block: { _ in
print("tapped")
})
... I get the following error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[MyApp.TapGestureRecognizer runAction]: unrecognized selector sent to class 0x105941598'
Any idea why?