Swift 3实现对collectionView标头进行抽头检测

Eri*_*ric 2 xcode ios swift swift3

我有一个带有多个节和标题的UICollectionView,我想检测一下节标题上的点击。

多亏了它,它对细胞的工作正常

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
Run Code Online (Sandbox Code Playgroud)

但是节标题没有特定内容。

我试图在collectionView上实现一个tapGestureRecognizer,它正在运行,但是在这种情况下,不再触发上述功能。

是否有一种简单的方法可以在单元格和节标题上实现抽头检测?

谢谢你的帮助 :)

Eri*_*ric 7

解决方案是将tapGestureRecognizer直接附加在该部分上,而不是附加在collectionView上。并感谢约翰的标签提示。

override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    ...
    let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "inputStartHeader", for: indexPath) as! GameInputStartHeader
    headerView.tag = indexPath.section

    let tapGestureRecognizer = UITapGestureRecognizer(target:self, action:#selector(tapDetected))
    headerView.addGestureRecognizer(tapGestureRecognizer)
    ...
}
Run Code Online (Sandbox Code Playgroud)

  • 在这里要小心,每次使标题出队时,您最终都会拥有很多识别器。您可以检查是否已存在识别器,或者在添加新识别器之前将其删除。 (7认同)