Jonathan Plackett Jonathan Plackett - 18 days ago 4x
iOS Question

UIViewcontroller as a subview not getting touch events

I'm trying to add a UIViewController to another UIViewController and then have a UIGestureRecogniser on it. Is this a bad idea? I don't seem to receive touch events to the sub viewcontroller at all. Can I enable them or is this just a foolish practice?


On main ViewController

let slider = SliderViewController()

slider.view.frame = CGRect(x: 0, y: 100, width: self.view.frame.size.width, height: self.view.frame.size.height/4)


slider.view.isUserInteractionEnabled = true // doesnt seem to make any difference

and on SliderViewController

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

print("touches began") // never gets called


If I present it with

self.present(slider, animated: true, completion: nil)

instead of adding as a subview, it works fine.


You probably need to add slider controller as a child controller too. By this way, UIKit will know that the view being added as a subview is tied to some view controller so it'll ensure that the child view controller will receive the same UI events such as user touches, orientation changes, lifecycle related callbacks like viewDidLoad, viewWillAppear etc.

To add slider as a child view controller, you should do:

slider.didMove(toParentViewController: self)

You should do the opposite in reverse order when removing the child view controller:

slider.willMove(toParentViewController: nil)