Skip to content

Instantly share code, notes, and snippets.

@bricklife
Last active October 28, 2023 10:26
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bricklife/ea0a72c39cec5ce1512c5344b951c3a1 to your computer and use it in GitHub Desktop.
Save bricklife/ea0a72c39cec5ce1512c5344b951c3a1 to your computer and use it in GitHub Desktop.
UITapGestureRecognizer in UICollectionView
//
// CollectionViewController.swift
// CollectionViewTouch
//
// Created by ooba on 30/01/2018.
// Copyright © 2018 ooba. All rights reserved.
//
import UIKit
private let reuseIdentifier = "Cell"
class CollectionViewController: UICollectionViewController {
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action: #selector(gesture(_:)))
tap.numberOfTapsRequired = 1
tap.numberOfTouchesRequired = 1
tap.delegate = self
collectionView?.addGestureRecognizer(tap)
}
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 3
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 6
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
// Configure the cell
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print(#function, indexPath)
}
@IBAction func gesture(_ sender: UITapGestureRecognizer) {
let point = sender.location(in: collectionView)
if let indexPath = collectionView?.indexPathForItem(at: point) {
print(#function, indexPath)
}
}
}
extension CollectionViewController: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
let point = touch.location(in: collectionView)
if let indexPath = collectionView?.indexPathForItem(at: point),
let cell = collectionView?.cellForItem(at: indexPath) {
return touch.location(in: cell).y > 50
}
return false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment