ios - UICollctionView 没有快速加载数组值

标签 ios uicollectionview swift4

UICollectionView 数组值未加载到 cellForItemAt indexPath 我正在使用以下代码

var tableData: [String] = ["Evo X", "458", "GTR"]

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.tableData.count
}

func collectionView(_ collectionView: UICollectionView,  cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
   let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collections", for: indexPath) as! CollectionViewCell
   let indexPath = self.tableData[indexPath.row]
   print("indexpath\(indexPath)")
   cell.celllabel.text = self.tableData[indexPath.row]
   cell.backgroundColor = UIColor.cyan
   return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    print("You selected cell #\(indexPath.item)!")
       label.text = self.tableData[indexPath.row]
}

数组值打印在

print("indexpath(indexPath)")

但未加载

cell.celllabel.text = self.tableData[indexPath.row]

我的输出是(控制台)

print("indexpath(indexPath)")

indexpathEvo X
indexpath458
indexpathGTR     

但是这一行出现错误

cell.celllabel.text = self.tableData[indexPath.row]

我的错误是

 Fatal error: Unexpectedly found nil while unwrapping an Optional value

我该如何解决这个问题?

enter image description here

最佳答案

问题

let indexPath = self.tableData[indexPath.row]
cell.celllabel.text = self.tableData[indexPath.row]

解决方案

//let indexPath = self.tableData[indexPath.row] not needed
cell.celllabel.text = self.tableData[indexPath.row]

解释:

您有一个字符串数组,您希望在单元格的 celllabel 组件中显示这些字符串。您从 indexPath.row 获取行,您需要做的就是获取索引 indexPath.row 处的字符串,因此

cell.celllabel.text = self.tableData[indexPath.row]

就够了。希望对你有帮助

编辑 1:

func collectionView(_ collectionView: UICollectionView,  cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
   let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collections", for: indexPath) as! CollectionViewCell
   cell.celllabel.text = self.tableData[indexPath.row]
   cell.backgroundColor = UIColor.cyan
   return cell
}

关于ios - UICollctionView 没有快速加载数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47900904/

相关文章:

ios - UICollectionViewCell 布局问题 iOS9

ios - 如何根据下载的图像大小创建动态大小的行高?

ios - 带图像的滞后滚动 TableView

ios - 如何让 UICollectionView 的一个单元格在其他单元格重新排序时忽略位置变化?

ios - 动态调整 UICollectionView 大小以确保没有项目间间距

swift - 在TableView Swift 4中显示Firebase数据

swift 4 : scrollViewDidScroll not working

ios - 如何在后台ios9中定期获取位置并将位置发送到服务器

ios - 我有一个 UIImage,它是在 UIImageView 中绘制的黑白图像的线条。如何在触摸时用颜色填充线条内部?

ios - 如何根据用户选择组合数组?