Reputation: 13
UICollectionView array values not loaded in cellForItemAt indexPath i am using following code
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]
}
Array values are print in
print("indexpath(indexPath)")
but not loaded in
cell.celllabel.text = self.tableData[indexPath.row]
my output is (console)
print("indexpath(indexPath)")
indexpathEvo X
indexpath458
indexpathGTR
but This line get the error
cell.celllabel.text = self.tableData[indexPath.row]
My error is
Fatal error: Unexpectedly found nil while unwrapping an Optional value
How can i fix that issue?
Upvotes: 0
Views: 112
Reputation: 20379
Issue
let indexPath = self.tableData[indexPath.row]
cell.celllabel.text = self.tableData[indexPath.row]
Solution
//let indexPath = self.tableData[indexPath.row] not needed
cell.celllabel.text = self.tableData[indexPath.row]
Explanation:
You have a array of strings which you want to show in cell's celllabel component. You get the row from indexPath.row
all you need to do is get the string at index indexPath.row
hence
cell.celllabel.text = self.tableData[indexPath.row]
is enough. Hope it helps
EDIT 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
}
Upvotes: 1