UISwipeGestureRecognizer does not recognize swipe gestures initiated outside of the view

func addSwipe() {
    self.isUserInteractionEnabled = true
    let directions: [UISwipeGestureRecognizerDirection] = [.right, .left]
    for direction in directions {
        let gesture = UISwipeGestureRecognizer(target: self, action: #selector(ViewCardContainer.handleSwipe(sender:)))
        gesture.direction = direction
        self.addGestureRecognizer(gesture)
    }
}

@objc func handleSwipe(sender: UISwipeGestureRecognizer) {
    print(sender.direction)
}

My UIViews:

+----------------+
|                |
|     +--------+ |
|  V1 |  V2    | |
+-----------------

I registered UISwipeGestureRecognizer in V2, but if swipe gestures started with V1 passing through V2, swipe gestures will not be recognized in V2.

Is there any way to make it work? Thanks in advance!

+4
source share
1 answer

EDIT: I created a working sample for you. You can scroll from the red square (v1) to the blue square (v2) and see in the log that swipe is detected.

https://github.com/QuantumProductions/so_46781856

import UIKit

class ViewController: UIViewController {
    var view2: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.black

        let view1 = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
        view1.backgroundColor = UIColor.red
        view.addSubview(view1)

        view2 = UIView(frame: CGRect(x: 100, y: 0, width: 100, height: 100))
        view2.backgroundColor = UIColor.blue
        view.addSubview(view2)

        let swipeRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(swipeDetected(_:)))
        swipeRecognizer.direction = .right
        view.addGestureRecognizer(swipeRecognizer)

    }

    func swipeDetected(_ sender: UIGestureRecognizer) {
        let location = sender.location(ofTouch: 0, in: view2)
        print("Location in view2")
        print(location)
        print("You swiped right")
    }
}

Original answer:

. . Apple, , , .

, V1 V2:

  • V1, V2
  • , V2 ( touch.locationInView: V2)
  • true, .

viewcontroller, self.view ( , , , func )

V1 V2, .

+7

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


All Articles