F.SO4 F.SO4 - 1 year ago 160
Swift Question

UITapGestureRecognizer doesn't work on UICollectionView header

I have a

with an header.

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

I've tried to add a
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

return header

And what happened it that:

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


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

Why is that?

Thank you!

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download