UICollctionView没有在swift中加载数组值

时间:2017-12-20 07:32:57

标签: ios uicollectionview swift4

未在cellForItemAt索引路径中加载的UICollectionView数组值我正在使用以下代码

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]
}

数组值以

打印
  

打印(" indexpath(indexPath)&#34)

但未加载

  

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

我的输出是(控制台)

  

打印(" indexpath(indexPath)&#34)

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

1 个答案:

答案 0 :(得分:1)

问题

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
}