UITapGestureRecognizer不能处理UICollectionView标头

时间:2016-07-29 12:21:49

标签: ios swift cocoa-touch

我有UICollectionView标题。

我想在用户点按标题时调用方法headerTapped

我试图在``方法中的标题中添加UITapGestureRecognizer

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
}

发生了什么:

当调用视图加载headerTapped时(甚至没有点击标题),然后当我点击标题时,它甚至被调用。

headerTapped()

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

为什么?

谢谢!

1 个答案:

答案 0 :(得分:0)

您的headerTapped方法必须符合Apple UITapGestureRecognizer docs

中此示例的格式

另请参阅UIGestureRecognzer docs以获取更多讨论。

此外,在您的headerTapped方法中,您需要检查手势识别器state,以便仅在点击手势结束时触发逻辑。

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