Anna
Anna

Reputation: 191

Detect First Touch on Viewcontroller in swift

I have UIViewController and it have many subviews on. Each subview can be Uibutton, other view controllers, UIView. How to detect when user first tap on screen anywhere. I have used TouchesBegan events but its not work on Subviews. Thanks So much!

Upvotes: 1

Views: 2939

Answers (3)

Anirudha Mahale
Anirudha Mahale

Reputation: 2596

Add gesture reconginse to the UIVIewController's view

// Add this in the ViewDidLoad method
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.didTapView(sender:)))
self.view.addGestureRecognizer(tapGesture)

@objc
func didTapView(sender: UITapGestureRecognizer) {
  print("View Tapped")
}

You will have to subclass the UI Element's class that you will be using and override the below method to pass touch event to below view in the view's hierarchy. Like so

class CustomView: UIView {
    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        print("Passing all touches to the next view (if any), in the view stack.")
        return false
    }
}

Now use this class in your storyboard, then it will pass the touch event to ViewController's view and hence it will call didTapView method. As you only want first touch event you can keep a flag to check if it's the first touch. One note please don't use UIButton if not needed.

Upvotes: 2

Anand
Anand

Reputation: 1946

Lets say your MainViewController has three subviews one UIButton, UIView and SubViewController. When these subviews are tapped / clicked, it can be detected in following ways.

UIButton: Add touchBegan event and have IBAction in MainViewController and capture it in MainViewController.

UIView: Add TapGesture as shown in below code to capture touch event in MainViewController.

SubViewController: Add TapGesture similar to UIView and capture touch event in SubViewController. Use Delegate pattern and inform the MainViewController about the SubViewController touch event.

By this way, you can detect the all touch event of the subviews in MainViewController. Hope it helps. If not, please let me know.

Tap Gesture Code

Add Tap Gesture to your view in viewDidLoad method.

var gestureTap = UITapGestureRecognizer(target: self, action: #selector(self.handleGestureTap(sender:)))
view.addGestureRecognizer(gestureTap)

Handler method:

@objc
func handleGestureTap(sender: UITapGestureRecognizer? = nil) {
  print("View Tapped")
}

Upvotes: 0

rog
rog

Reputation: 73

Hi did you make sure that you create referencing outlets to the class?

you can check ventuz's answer in this question: UIView touch event in controller

Upvotes: 1

Related Questions