Handle Touch in UiCollectionView?

While tapping on scrolling controllers (like UIScrollView, UITableView, UICollection etc) does not call touchesBegan method. because they have their own selector method. To handle such situation, you need to create UITapGesture on UICollectionView. While tapping on UICollectionView, its selector method called and do what ever you want.

Here are the link that guide you. how to create double Tap Gesture on UICollectionView. with help of this you can created single Tap gesture as well.

Collection View + Double Tap Gesture

Edit : Do the following changes, it work fine.

Step 1 : Declare handleTap in SwipeMenuViewController.

func handleTap(sender: UITapGestureRecognizer) {

        println("called swipe")

    }

Step 2 : Create global variable of SwipeMenuViewController controller. that is out side of viewDidLoad()

var vc2 = SwipeMenuViewController()

enter image description here

Step 3 : Declare TapGesture in viewDidLoad()

var tap = UITapGestureRecognizer(target: vc2, action : "handleTap:")
        tap.numberOfTapsRequired = 1
        self.collectionView.addGestureRecognizer(tap)

Output :

called swipe

Hope this help you.


You can add a UITapGestureRecognizer to the UICollectionView and create an action to dismiss the view if the user touch outside your collection or anywhere.

Step 1 Create a tap gesture for dismiss the view

override func viewDidLoad() {
    super.viewDidLoad()
     ...

    let tap = UITapGestureRecognizer(target: self, action: #selector(didTapOutsideCollectionView(recognizer:)))
    tap.numberOfTapsRequired = 1
    self.collectionView.addGestureRecognizer(tap)
}

Step 2 With the tap location implement your desired action

@objc func didTapOutsideCollectionView(recognizer: UITapGestureRecognizer){
    let tapLocation = recognizer.location(in: self.view)
    //The point is outside of collection cell
    if collectionView.indexPathForItem(at: tapLocation) == nil {
         dismiss(animated: true, completion: nil)
    }
}