ios - UITapGestureRecognizer 不适用于 UICollectionView header

标签 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
}

发生了什么:

当 View 加载 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))
    }

这是为什么?

谢谢!

最佳答案

您的 headerTapped 方法需要采用 Apple UITapGestureRecognizer docs 本示例中的形式。

另请参阅UIGestureRecognzer docs进行更多讨论。

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

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

关于ios - UITapGestureRecognizer 不适用于 UICollectionView header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38658735/

相关文章:

ios - 在 iPhone 中连续播放 1 个声音片段而不会出现任何中断

ios - 获取当前界面方向的不同方式?

generics - 如何在 Swift 中调用不明确的泛型函数?

uitableview - 单击tableviewcell上的按钮时如何刷新tableview

ios - 用于自定义绘图的子类 UIView,上下文为空

iphone - 将数据从委托(delegate)传递到 UIViewController

ios - 图像行和列的教程?

ios - 连续语音识别。使用 SFSpeechRecognizer (ios10-beta)

ios - 如何使用 XCTest 测试导航栏是否未设置为 objective-C 中的特定颜色?

ios - Swift Bundle ID 错误中的 GCM