簡體   English   中英

Swift 4:UITableView cellForRow 崩潰

[英]Swift 4 : UITableView cellForRow crash

我無法理解我做錯了什么。 我有一個名為 TblView_Categorie 的 UITableView,我想要做的是在所需的索引路徑中獲取單元格:

這是我的代碼:

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

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

問題是如果 MyRecordIndex 顯示在屏幕上(不需要滾動)一切正常

如果 MyRecordIndex 未顯示在屏幕上(需要滾動),則會出現此錯誤:

線程 1:致命錯誤:在展開 Optional 值時意外發現 nil

如果我手動滾動到所需的索引並輸入所需的 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
}

// 更新代碼和崩潰屏幕截圖

崩潰和代碼

你不能顯式解壓縮

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

由於單元格我不可見所以它將為零 - >崩潰

試試

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

 if(cell != nil)
 {

 }

編輯:滾動到單元格並在 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)
 {

 }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM