【问题标题】:How to get data from a selected UICollectionView cell?如何从选定的 UICollectionView 单元格中获取数据?
【发布时间】:2016-05-06 10:11:04
【问题描述】:

我的ViewController 由一个UIButton 和一个UICollectionView 组成,它有4 个单元格。我将选择任何单元格,当我点击按钮时,我只想从选定的UICollectionViewCell 中获取数据。 UIButtonUICollectionViewUICollectionViewCell 之外。

【问题讨论】:

  • 您需要哪种类型的数据?请说明所有事情,仍然是您尝试的内容。
  • @Mitesh:在单元格中有一些文本数据,如姓名年龄工资等。
  • This 可能会解决您的问题。
  • @werediver 这与我的问题不太相关。我想在 uibutton 点击​​时仅选择 uicollectionviewcell 中的数据
  • 那你的问题到底是什么?无法确定选定的单元格索引路径?

标签: ios objective-c swift uicollectionview


【解决方案1】:

您可以使用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
      }
   }

【讨论】:

猜你喜欢
  • 2021-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多