Swift: Click onto cell of UICollectionView and open AlertViewController
try next:
extension HomeViewController: UICollectionViewDataSource, UICollectionViewDelegate {
}
or
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
...
cell.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tap(_:))))
}
func tap(_ sender: UITapGestureRecognizer) {
let location = sender.location(in: self.collectionView)
let indexPath = self.collectionView.indexPathForItem(at: location)
if let index = indexPath {
print("Got clicked on index: \(index)!")
}
}
This is the version using the delegate:
extension HomeViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("item at \(indexPath.section)/\(indexPath.item) tapped")
}
}
Instead of using the extension you can also just add UICollectionViewDelegate and the collectionView(...didSelectItemAt:...) function to the class HomeViewController directly:
class HomeViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("item at \(indexPath.section)/\(indexPath.item) tapped")
}
}