【问题标题】:How to make cell index path.row == an items index in array?如何使单元格索引 path.row == 数组中的项目索引?
【发布时间】:2018-07-06 03:00:11
【问题描述】:

我有一个包含 100 个项目的数组,名为 cellNames,类型为 String。我有一个由 1 个部分组成的集合视图,其中包含 100 个 customCollectionViewCell 行。我正在寻找这样的东西-

for cellName in cellNames {
   if cellName.index == cellNames[indexpath.row] {
     let cellName = cell.nameTextField
    }
}

总而言之,我需要索引 0...100 == cellForRowAt 0...100 的 cellName

【问题讨论】:

  • 你想用cellNames 填充你的collectionView吗?不清楚你在问什么
  • 我的收藏视图有 100 个单元格:CustomCollectionViewCell。 customcollectionviewcell 有一个名为 nameTextField 的文本字段。我需要从数组中取出 100 个项目中的每一个,并用数组中的一个 cellName 填充每个单元格。但我需要它们以便 cellName[0] 填充 cell@[indexPath.row[0]]
  • 你想要什么?你想将每个单元格与索引路径结合起来还是想知道哪个单元格是第三个例如

标签: arrays swift uicollectionview


【解决方案1】:

看起来您正在创建 100 个静态单元格并尝试使用 cellNames 填充它们。正确的方法是遵守UICollectionViewDataSource 并将项目数设置为cellNames 的计数,并使用cellForItemAt 中提供的indexPath 来访问数组的每个元素。

class ViewController: UIViewController {

    let cellNames = ["1", "2", "3"] // ....

    override func viewDidLoad() {
        super.viewDidLoad()

    }
}

extension ViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return cellNames.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "customCellId", for: indexPath) as! CustomCell
        let cellName = cellNames[indexPath.item]
        cell.nameTextField.text = cellName
        return cell
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-05
    • 1970-01-01
    • 2014-01-30
    • 2011-01-28
    • 2018-03-24
    • 2013-09-14
    • 2018-08-23
    相关资源
    最近更新 更多