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

New*_*ner 2 objective-c ios uicollectionview swift

ViewController的a UIButton和a UICollectionView由4个单元组成.我将选择任何单元格,当我点击按钮时,我想从仅选中的数据中获取数据UICollectionViewCell.的UIButton是外面的UICollectionViewUICollectionViewCell.

Seb*_*ldt 20

您可以使用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
      }
   }
Run Code Online (Sandbox Code Playgroud)