Last active
October 28, 2023 10:26
-
-
Save bricklife/ea0a72c39cec5ce1512c5344b951c3a1 to your computer and use it in GitHub Desktop.
UITapGestureRecognizer in UICollectionView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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