iosswiftuigesturerecognizerxcode11.3

Swipe gesture is not being called on a subview inside a present view controller


I presented a view controller and I have a subview in it. I added a swipe gesture on the subview. The swipe gesture is not being called. Instead, the presented view controller is trying to dismiss itself i.e. going down. How do I override the swipe gesture to be recognised by the subview instead of the super view. When I implemented swipe on a static view controller, it works as expected.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var viewSwipe: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(swipeUp(_:)))
        swipeUp.direction = UISwipeGestureRecognizer.Direction.up
        self.viewSwipe.addGestureRecognizer(swipeUp)

        let swipedown = UISwipeGestureRecognizer(target: self, action: #selector(swipeDown(_:)))
        swipedown.direction = UISwipeGestureRecognizer.Direction.down
        self.viewSwipe.addGestureRecognizer(swipedown)
    }

    @objc func swipeUp(_ gesture: UISwipeGestureRecognizer) {
        print("swiped up")
    }

    @objc func swipeDown(_ gesture: UISwipeGestureRecognizer) {
        print("swiped down")
    }
}

The red area needs to get swipe

screenshot


Solution

  • Add Gesture only in view and you can also add any direction on gesture. Here i put Small example, you can refer this code for your problem.

    Get 1 for Right Direction and 2 For Left Direction

    Example :

    import UIKit
    
    class ViewController: UIViewController,UIGestureRecognizerDelegate{
    
     @IBOutlet weak var viewGray: UIView!
     @IBOutlet weak var viewRed: UIView!
    
     override func viewDidLoad() {
         super.viewDidLoad()
    
       self.navigationController?.interactivePopGestureRecognizer?.delegate = self
    
       let directions: [UISwipeGestureRecognizer.Direction] = [.right, .left]
         for direction in directions {
            let gesture = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(sender:)))
            gesture.direction = direction
            gesture.delegate = self
            self.viewRed.addGestureRecognizer(gesture)
         }
      }
    
      @objc func handleSwipe(sender: UISwipeGestureRecognizer) {
        print(sender.direction)
      }
    
       func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
           return true
       }
    
      func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
          return true
      }
    }
    

    enter image description here