Search code examples
iosswiftuigesturerecognizergesture

how to add gesture recognizer to ViewController and to its Children?


I am making app like in Euro Sport. My rootviewController is pageViewController which has 3 VCs. Swiping left and right you can change the VC. Next, I added sidebarmenu. I want to add gesture recognizer to the whole rootViewController. This is how I am adding gesture:

 self.exitPanGesture = UIPanGestureRecognizer()
        self.exitPanGesture.addTarget(self, action:"handleOffstagePan:")
        self.sourceViewController.view.addGestureRecognizer(self.exitPanGesture)
        self.sourceViewController.navigationController?.view.addGestureRecognizer(self.exitPanGesture)

When I drag rootviewController tapping on navigation bar it works. But the other parts like segmentcontrol, and pageContent doesnt work.

I am setting sourceViewController here:

 func resetToMainPage(index: Int!) {
    /* Getting the page View controller */
    mainPageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("MainPageViewController") as UIPageViewController
    self.mainPageViewController.dataSource = self
    self.mainPageViewController.delegate = self

    pageContentViewController = self.viewControllerAtIndex(index)

   // self.transtionManger.sourceViewController = pageContentViewController // adding swipe to the pageContentViewControlle in order to close menu
    self.transtionManger.sourceViewController = mainPageViewController
    self.mainPageViewController.setViewControllers([pageContentViewController!], direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil)


    self.mainPageViewController.view.frame = CGRectMake(0, 102, self.view.frame.width, self.view.frame.height)
    self.addChildViewController(mainPageViewController)
    self.view.addSubview(mainPageViewController.view)
    self.mainPageViewController.didMoveToParentViewController(self)

}

So, My question is how to add gesture recognizer to the whole rootViewController, including navbar, segmentcontrol, pageviewcontrol?


Solution

  • A gesture recognizer can only be attached to one view. So the lines below mean that only navigationController?.view is getting the gesture added.

    self.sourceViewController.view.addGestureRecognizer(self.exitPanGesture)
    self.sourceViewController.navigationController?.view.addGestureRecognizer(self.exitPanGesture)
    

    You can just duplicate the gesture recognizer for each view you want to have it on and then add them all that way.

    self.exitPanGesture1 = UIPanGestureRecognizer()
    self.exitPanGesture1.addTarget(self, action:"handleOffstagePan:")
    self.sourceViewController.view.addGestureRecognizer(self.exitPanGesture1)
    
    self.exitPanGesture2 = UIPanGestureRecognizer()
    self.exitPanGesture2.addTarget(self, action:"handleOffstagePan:")
    self.sourceViewController.navigationController?.view.addGestureRecognizer(self.exitPanGesture2)