4

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.

9
  • which type of data you need? please spicify all thing and still what you try. Commented May 6, 2016 at 10:17
  • @Mitesh: In cell has some text data like name age salary etc. Commented May 6, 2016 at 10:20
  • This may solve your question. Commented May 6, 2016 at 10:21
  • @werediver This is not very related to my queston. I want data from only selected uicollectionviewcell on uibutton click Commented May 6, 2016 at 10:35
  • Then what exactly is your issue? You can't determine selected cell index path? Commented May 6, 2016 at 10:42

1 Answer 1

22

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
      }
   }
Sign up to request clarification or add additional context in comments.

2 Comments

@Sebastian If I want to access Image/imageData ?
I am having a similar issue, can you see the link below:stackoverflow.com/questions/43701497/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.