Search code examples
iosswiftuicollectionviewtouchuigesturerecognizer

Handle Touch in UiCollectionView?


I have this big UICollectionView occupying major part of screen and there is a UIButton that shows a menu. I want to hide the menu when the user taps on any side of the screen which becomes unfortunately any part of UICollectionView for me. Tried on other view the below code, it works well...but not for UICollectionView. The function does not gets called.

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {            
   hidemenu()
   self.view.endEditing(true)            
}

What is the problem? Thanks for your time.

OR How to trigger touchesBegan in the UIViewController where UICollectionView resides

Here is the project.


Solution

  • 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.