2015-03-13 70 views
1

我有單元格的自定義類,我有UItableView,它顯示單元格的元素(如標籤和圖像),我也使用parse.com作爲應用程序的後端,當我刷新表格時,最後一個單元格會重複第一個單元格,所以我一直在尋找解決方案來防止重複單元格,這是我的代碼爲cellForRowAtIndexPathUITableView重複單元格如何防止它? Swift

非常感謝您的幫助。

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     var myCell:Cell = tableView.dequeueReusableCellWithIdentifier("myCell") as Cell 

     // Configure the cell... 

     myCell.label1.text = Array1[indexPath.row] 
     myCell.label2.text = Array2[indexPath.row] 
     myCell.label3.text = Array3[indexPath.row] 
     myCell.label4.text = Array4[indexPath.row] 
     myCell.postedImage.layer.cornerRadius = myCell.postedImage.frame.size.width/2 
     myCell.postedImage.clipsToBounds = true 
     //get the image from parse 
    imagefiles[indexPath.row].getDataInBackgroundWithBlock{(imageData: NSData!, error:NSError!) -> Void in 
      if error == nil { 
       let image = UIImage(data: imageData) 
       myCell.postedImage.image = image    
       } 
      } 
     }    
     return myCell 
    }   

回答

2

好幾天後,我發現問題並修復它,它不是從cellForRowAtIndexPath函數,它是從代碼與解析通信,我添加了一個代碼,以防止重複單元格所有的元素都屬於這個單元格,所以我的代碼看起來像這樣

Feed.findObjectsInBackgroundWithBlock{ (objects: [AnyObject]!, error: NSError!) -> Void in 
     //here is the fix i have done 
     self.Array1.removeAll(keepCapacity: true) 
     self.Array2.removeAll(keepCapacity: true) 
     self.Array3.removeAll(keepCapacity: true) 
     self.Array4.removeAll(keepCapacity: true) 
     self.Array5.removeAll(keepCapacity: true) 
if error == nil { 

} else { 

} 
4

有兩個問題與此代碼:

1)由於細胞被緩存,有可能是你回來的最後一個單元具有從先前的小區配置的數據。其結果是它會顯示來自舊單元格的數據和圖像。

這可以通過初始化myCell.postedImage.imagenil或一些佔位符圖像來解決。

2)你正在做一個緩存單元的異步請求。這意味着到``完成時,myCell可以重新用於另一行。所以你現在將圖像設置在不同的單元格上。這也會導致你描述的結果混亂。

+0

所以,你可以幫我一下嗎? – 2015-03-13 16:06:36

+0

我已經使用準備在自定義類單元格中重用,並使myCell.postedImage.image =零,問題仍然存在,任何幫助將不勝感激 – 2015-03-14 20:03:16

相關問題