Reputation: 411
I can't understand what I am doing wrong. I have a UITableView called TblView_Categorie, what I am trying to do is get the cell at desired indexpath:
Here is my code:
let myRecordindex = IndexPath(row: myRecordcheck, section: 0)
let cell = tblViewcategorie.cellForRow(at: myRecordindex) as! categorieTVC
The problem is if MyRecordIndex is shown screen (no scrolling needed) everything working fine
If MyRecordIndex is not shown on screen (scrolling needed) I have this error:
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
If I manually scroll to the desired index and I enter the desired MyRecordIndex everything working fine
I tried to automatically scrolling using the code below: the scroll work but still same error
self.tblViewCategorie.scrollToRow(at: myRecordindex, at: UITableViewScrollPosition.middle, animated: true)
Why I have this error? All I am trying to do is getting the cell at desired indexpath to change color, font, etc.
// UPDATE cellForRowAt Implementation
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! categorieTVC
if let categorieName = self.fetchedResultsController.object(at: indexPath).categorieName{
cell.setListeDesCategories(categorieName: categorieName)
}
return cell
}
// Update code and crash screen shot
Upvotes: 2
Views: 1618
Reputation: 100541
You can't explicit unwarp
let cell = TblView_Categorie.cellForRow(at: MyRecordIndex) as! CategorieTVC
as cell my be not visible so it will be nil -> crash
try
let cell = TblView_Categorie.cellForRow(at: MyRecordIndex) as? CategorieTVC
if(cell != nil)
{
}
Edit : scroll to the cell and dispatch after the cellForRow
let myRecordindex = IndexPath(row: myRecordcheck, section: 0)
self.tblViewCategorie.scrollToRow(at: myRecordindex, at: UITableViewScrollPosition.middle, animated: true)
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0 )) {
let cell = TblView_Categorie.cellForRow(at: MyRecordIndex) as? CategorieTVC
if(cell != nil)
{
}
}
Upvotes: 3