【问题标题】:UICollctionView not loading Array Values in swiftUIColllctionView 没有快速加载数组值
【发布时间】:2017-12-20 07:32:56
【问题描述】:

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

我该如何解决这个问题?

【问题讨论】:

  • is CollectionViewCell 有一个名为 celllabel 的 textField/textView ???
  • CollectionViewCell 有标签
  • 感谢您的回复
  • 请尝试 indexPath.item 而不是 indexPath.row。

标签: ios uicollectionview swift4


【解决方案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
}

【讨论】:

  • 我已经尝试过这些线路。但我遇到了同样的问题。但是命令 (//cell.celllabel.text = self.tableData[indexPath.row]) 这些行我得到了输出。当我选择“didSelectItemAt indexPath”时显示值。但不显示collectionviewcell行中的数组值
  • @ramkumar :按原样使用我在 EDIT 1 中发布的 cellForItemAt 并让我知道它是否有效
  • 我使用模拟器添加了我的截图
  • @ramkumar : 实现 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 并返回单元格大小以查看单元格和标签
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-03
  • 1970-01-01
  • 2022-08-07
  • 2019-02-13
  • 2013-07-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多