简体   繁体   中英

How to trigger multiple UIGestureRecognizers without lifting finger from screen

I have adjacent views on the screen, and each have a different UIGestureRecognizer . What I want is if I touch down in one view and move into an adjacent view, the adjacent view's gesture recognizer will start detecting the touches.

What is currently happening is if I touch down in one view and move out of that view's frame, the initial view's gesture recognizer will continue to receive calls to touchChanged until my finger has lifted. And it doesn't matter if I change the state of the gesture recognizer to .ended , .failed , or .cancelled , no other gesture recognizers will receive calls to their touch methods until my finger is lifted.

How can I ensure a gesture recognizer will be triggered when the touch is in its view's bounds, and end when it leaves them, without having to handle touch events from the superview?

Here is the custom UIGestureRecognizer I implemented to do this:

class GestureRecognizer: UIGestureRecognizer, UIGestureRecognizerDelegate {
    override init(target: Any?, action: Selector?) {
        super.init(target: target, action: action)
        delegate = self
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
        super.touchesBegan(touches, with: event)
        state = .began
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
        super.touchesMoved(touches, with: event)
        if state == .began {state = .ended}
        else {state = .began}
    }

    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return otherGestureRecognizer is GestureRecognizer
    }
}

You can do this, Just write this delegate method in your controller, and return true.

read this once. https://developer.apple.com/reference/uikit/uigesturerecognizerdelegate/1624208-gesturerecognizer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM