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
我该如何解决这个问题?
最佳答案
问题
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/