Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data from a selected UICollectionView cell?

My ViewController consists of a UIButton and a UICollectionView which has 4 cells. I will select any cell and when I tap the button I want to get the data from only the selected UICollectionViewCell. The UIButton is outside the UICollectionView and UICollectionViewCell.

like image 789
New-Learner Avatar asked Nov 29 '22 23:11

New-Learner


1 Answers

You can use indexPathsForSelectedItems to get the indexPaths for all selected Items. After you requested all the IndexPath you can simply ask the collectionView for the corresponding cell to get your Data.

import UIKit

class TestCell: UICollectionViewCell {
    var data : String?
}

class ViewController: UIViewController {

    var model = [["1","2","3","4"]]
    @IBOutlet weak var collectionView: UICollectionView?

    @IBAction func buttonTapped(sender: AnyObject) {
        if let collectionView = self.collectionView,
            let indexPath = collectionView.indexPathsForSelectedItems?.first,
            let cell = collectionView.cellForItem(at: indexPath) as? TestCell,
            let data = cell.data {
                    print(data)
        }
    }
}

extension ViewController : UICollectionViewDataSource {
   func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return model.count
   }

   func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return model[section].count
   }

   func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCellWithReuseIdentifier("test", forIndexPath: indexPath) as! TestCell
            cell.data = self.model[indexPath.section][indexPath.row]
            return cell
      }
   }
like image 64
Sebastian Boldt Avatar answered Dec 06 '22 00:12

Sebastian Boldt