我的ViewController
由UIButton
和UICollectionView
组成,其中包含4个单元格。我将选择任何单元格,当我点击按钮时,我想仅从选定的UICollectionViewCell
获取数据。
UIButton
位于UICollectionView
和UICollectionViewCell
之外。
答案 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
}
}