F.SO4 F.SO4 - 4 months ago 49
Swift Question

UITapGestureRecognizer doesn't work on UICollectionView header

I have a

UICollectionView
with an header.

I want to call the method
headerTapped
when the user tap on the header.

I've tried to add a
UITapGestureRecognizer
to the header in the `` method like that:

override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
let header = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "likesHeader", forIndexPath: indexPath) as! LikesCollectionReusableView

header.postsCounter.text = "\(self.likedBasicPosts.count)"

//Adding gesture recognizer
let tapRecognizer = UITapGestureRecognizer(target: self, action: Selector(headerTapped()))
tapRecognizer.numberOfTapsRequired = 1
header.addGestureRecognizer(tapRecognizer)

return header
}


And what happened it that:

When the view load
headerTapped
is being called (without even tapping on the header), and then when I tap on the header it does;t even being called.

headerTapped()
:

private func likesHeaderWasTapped() {
if self.expandedSections.containsObject(1) {
self.expandedSections.removeObject(1)
} else {
self.expandedSections.addObject(1)
}
self.smallPhotosCollectionView.reloadSections(NSIndexSet(index: 1))
}


Why is that?

Thank you!

Answer

Your headerTapped method needs to be of the form in this example from the Apple UITapGestureRecognizer docs

Also see the UIGestureRecognzer docs for more discussion.

Also, in your headerTapped method, you need to check the gesture recognizer state so that you only trigger your logic when the tap gesture has ended.

func handleTap(sender: UITapGestureRecognizer) {
    if sender.state == .Ended {
        // handling code
    }
}
Comments