I add a UIGestureReconizer to a view to detect Touch Down action, but then the buttons above the view won't work anymore

≡放荡痞女 提交于 2020-01-25 10:39:05

问题


I have a view which needs to detect "Touch Down" action on the full view, after I found out normal UITapGestureRecognizer can't accomplish it, I customize UIestureRecognizer class to achieve it, using this.

So it does work, but I have several buttons on the view, after I can detect the Touch Down action for the view, those buttons stop to work. I need both of them to work, the view to detect Touch Down and the buttons can be pressed above the view. How can I achieve it?

To be clear, those buttons just need to detect normal Touch Up Inside action, only the view need to detect Touch Down action. Also, when touch events happen on the buttons, the view doesn't need to do react to the touch event.

Thanks.

import UIKit
import UIKit.UIGestureRecognizerSubclass

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let t = SingleTouchDownGestureRecognizer(target: self, action: #selector(handleTap(sender:)))
        self.view.addGestureRecognizer(t)

    }

    @objc func handleTap(sender: UITapGestureRecognizer? = nil) {

        self.view.backgroundColor = #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1)
        UIView.animate(withDuration: 1) {
            self.view.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        }

    }
    @IBAction func testBtnPressed(_ sender: Any) {
        print("testBtnPressed!")
    }

}

class SingleTouchDownGestureRecognizer: UIGestureRecognizer {
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
        if self.state == .possible {
            self.state = .recognized
        }
    }
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
        self.state = .failed
    }
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
        self.state = .failed
    }
}

回答1:


You could compare that event in touchesBegan has touches for the view that is the same as the view to witch your gesture recognizer was assigned

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
        guard let view = self.view else { return }
        guard let touches = event.touches(for: view) else { return }
        super.touchesBegan(touches, with: event)
        if self.state == .possible {
            self.state = .recognized
        }
    }


来源:https://stackoverflow.com/questions/56816162/i-add-a-uigesturereconizer-to-a-view-to-detect-touch-down-action-but-then-the-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!