gpt4 book ai didi

ios - swift 4 : UITableView cellForRow crash

转载 作者:塔克拉玛干 更新时间:2023-11-02 10:21:28 32 4
gpt4 key购买 nike

我不明白我做错了什么。我有一个名为 TblView_Categorie 的 UITableView,我想要做的是在所需的索引路径处获取单元格:

这是我的代码:

let myRecordindex = IndexPath(row: myRecordcheck, section: 0)

let cell = tblViewcategorie.cellForRow(at: myRecordindex) as! categorieTVC

问题是如果 MyRecordIndex 显示在屏幕上(不需要滚动)一切正常

如果 MyRecordIndex 没有显示在屏幕上(需要滚动)我有这个错误:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

如果我手动滚动到所需的索引并输入所需的 MyRecordIndex 一切正常

我尝试使用下面的代码自动滚动:滚动有效但仍然有同样的错误

   self.tblViewCategorie.scrollToRow(at: myRecordindex, at: UITableViewScrollPosition.middle, animated: true)

为什么我有这个错误?我要做的就是让单元格位于所需的索引路径以更改颜色、字体等。

//更新 cellForRowAt 实现

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
}

//更新代码和崩溃屏幕截图

Crash and code

最佳答案

你不能显式反扭曲

 let cell = TblView_Categorie.cellForRow(at: MyRecordIndex) as! CategorieTVC 

因为我的单元格不可见所以它会是 nil -> 崩溃

尝试

 let cell = TblView_Categorie.cellForRow(at: MyRecordIndex) as? CategorieTVC 

if(cell != nil)
{

}

编辑:滚动到单元格并在 cellForRow 之后分派(dispatch)

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)
{

}
}

关于ios - swift 4 : UITableView cellForRow crash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48630808/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com