Closing for UIGestureRecognizers

I was wondering if it is possible to initialize with a UIGestureRecognizerblock instead of creating a separate function for it.
In Swift 3, I believe this was introduced for timers.

I implemented something similar to the code posted here , since it did not 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 TapGestureRecognizeras follows:

TapGestureRecognizer(block: { _ in
    print("tapped")
})

... I get the following error:

The application terminated due to an uncaught exception "NSInvalidArgumentException", reason: "+ [MyApp.TapGestureRecognizer runAction]: unrecognized selector sent to class 0x105941598 '

Any idea why?

+4
1

, TapGestureRecognizer. runAction , super.init, , : +[MyApp.TapGestureRecognizer runAction]. , runAction .

:

init() {
    super.init(target: TapGestureRecognizer.self, action: #selector(runAction))
    self.removeTarget(TapGestureRecognizer.self, action: #selector(runAction))
    self.addTarget(self, action: #selector(runAction))
}

- , .

+4

Source: https://habr.com/ru/post/1675278/


All Articles