Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Click onto cell of UICollectionView and open AlertViewController

In my app, I am using an UICollectionView. Now I want to develop an UIAlertController, when clicking onto any cell of the collection view. I started with following code:

extension HomeViewController: UICollectionViewDataSource {

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    …
}

// specify cells
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    ….
}

// called when widget is moved
func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        …
}

// called when clicked
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    print("Got clicked!")
}

}

But somehow, "Got clicked!" is never printed.

like image 226
Alexander Jeitler-Stehr Avatar asked Oct 28 '17 08:10

Alexander Jeitler-Stehr


2 Answers

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)!")
   }         
}
like image 132
a.afanasiev Avatar answered Nov 14 '22 20:11

a.afanasiev


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")
  }
}
like image 40
randomcontrol Avatar answered Nov 14 '22 22:11

randomcontrol