如何从选定的UICollectionView单元格获取数据?

时间:2016-05-06 10:11:05

标签: ios objective-c swift uicollectionview

我的ViewControllerUIButtonUICollectionView组成,其中包含4个单元格。我将选择任何单元格,当我点击按钮时,我想仅从选定的UICollectionViewCell获取数据。 UIButton位于UICollectionViewUICollectionViewCell之外。

1 个答案:

答案 0 :(得分:16)

您可以使用indexPathsForSelectedItems获取所有选定项目的indexPaths。在您请求所有IndexPath之后,您只需向collectionView询问相应的单元格即可获取您的数据。

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
      }
   }