iOS Tap gesture state begin doesn't hit

前端 未结 5 1050
半阙折子戏
半阙折子戏 2021-01-12 13:56

I have made a view clickable with a tap gesture recognizer, which is working just fine. But I want to highlight the view when the touch happens en remove it when the touch e

5条回答
  •  醉梦人生
    2021-01-12 14:44

    Quite an old question, but still. Hope it will be helpful for somebody. If I've got the author's question right, the idea is to detect whether the tap has began recognizing and to perform an action. Like if you don't want target to trigger only when the user releases the finger but already when he touch it for the very first time.

    An easy way to do so is to make an extension for UITapGestureRecognizer like below:

    fileprivate class ModTapGestureRecognizer: UITapGestureRecognizer {
        
        var onTouchesBegan: (() -> Void)?
        
        override func touchesBegan(_ touches: Set, with event: UIEvent) {
            onTouchesBegan?()
            super.touchesBegan(touches, with: event)
        } 
    }
    

    Later in your code you can use it like so:

    let tapRecognizer = ModTapGestureRecognizer()
    tapRecognizer.addTarget(self, action: #selector(didTapped))
    tapRecognizer.onTouchesBegan = {
       print("Yep, it works")
    }
    yourView.addGestureRecognizer(tapRecognizer)
    

    And you're awesome!

提交回复
热议问题