Lahav Lahav - 6 months ago 15
iOS Question

UITapGestureRecognizer won't work in UIScrollView

I have a

UIScrollView
with paging enabled that contains two view controllers: vc0, vc1. The scrollview is contained in a UIView (called "dummyView"), which is contained in its own view controller.

The issue is that vc1 does not respond to touches when the view controller that contains the scrollview is set to the initial view controller. If vc1 is set to the initial view controller however, vc1 responds to touch events just fine

Why does vc1 not respond to touches when it is viewed through the scrollView?

I have included the viewdidLoad() of the view controller that contains the scrollview, where I set up the scrollview and all of its subviews.

import UIKit

class ViewController: UIViewController, UIGestureRecognizerDelegate {

@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var dummyView: UIView!

override func viewDidLoad() {
super.viewDidLoad()

scrollView.contentSize = CGSizeMake(self.view.frame.width * 2, self.view.frame.height);
dummyView.frame.size = scrollView.contentSize

createConstraintsForDummyView()

let vc0 = self.storyboard?.instantiateViewControllerWithIdentifier("vc0") as! ViewController0

self.addChildViewController(vc0)
self.dummyView.addSubview(vc0.view)
vc0.didMoveToParentViewController(self)

createConstraintsForVC0(vc0)

let vc1 = self.storyboard?.instantiateViewControllerWithIdentifier("vc1")

var frame1 = vc1!.view.frame
frame1.origin.x = self.view.frame.size.width
vc1!.view.frame = frame1

self.addChildViewController(vc1!)
self.dummyView.addSubview(vc1!.view)
vc1!.didMoveToParentViewController(self)

createConstraintsForVC1(vc1)
}


EDIT: I've included the class for vc1

import UIKit

class ViewController1: UIViewController, UIGestureRecognizerDelegate {

func handleTap(recognizer: UITapGestureRecognizer){
print("Tapped!")
}

override func viewDidLoad() {
super.viewDidLoad()

let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
tap.delegate = self
self.view.addGestureRecognizer(tap)

// Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}

Answer

As discussed here

The dummyView was causing problems.
The solution is to remove the dummyView and use the scrollView instead.

Comments