2017-09-27 11 views
0

以編程方式將視圖添加到tableView單元格中,從而導致滾動干擾和速度變慢。我在代理函數「CellForRowAt」中以編程方式將視圖添加到單元格中。我通過委託函數「WillDisplay」嘗試了它,但結果是一樣的。 實現這一目標的最佳解決方案是什麼?以編程方式將視圖添加到tableView單元格中,使滾動乾和慢

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: 
     "cell", for: indexPath) as! CustomCell 
     addViewsInCell(cell: cell, indexPath: indexPath) 
     return cell 
} 

func addViewsInCell(cell: CustomCell, indexPath: IndexPath) { 
     //here i am adding some views programmatically 
     for i in 0..<3 { 
      let customView: CustomView = Bundle.main.loadNibNamed("CustomView", owner: self, options: nil)![0] as! customView 
      cell.customViewPlacement.addSubview(customView) 
     } 
} 
+1

您能否請出示您的代碼? –

+3

本週早些時候我的水晶球破裂了,你可以發佈一些代碼嗎? –

+0

傢伙,請參閱最新的問題。 –

回答

0

單元格視圖被重複使用。每次在cellForRowAt indexPath:中添加子視圖時,最終都會生成相同子視圖的多個副本。相反,您應該檢查該子視圖是否已添加。您可以用標記標記子視圖,然後使用viewWithTag方法來測試它的存在。

0

請勿在tableView: cellForRowAt indexPath:內添加任何子視圖/自定義視圖。這將導致這些子視圖在表格視圖加載時重複添加。相反,如果以編程方式工作,請創建UITableViewCell的子類並在該子類內創建子視圖。否則,如果您正在使用故事板,則可以創建一個動態原型單元格。

+0

如果我想將每個行中的自定義視圖多次添加到一個表中,該怎麼辦? 例如: FUNC addViewsInCell(細胞:CustomCell,indexPath:IndexPath){// 我在這裏通過包括筆尖編程 對於i在0添加視圖.. <3 { 讓customView:CustomView = Bundle.main .loadNibNamed(「CustomView」,owner:self,options:nil)![0] as! customView cell.customViewPlacement.addSubview(customView) } } –

相關問題