【问题标题】:UITableView repeats cells how to prevent it? SwiftUITableView 重复单元格如何防止呢?迅速
【发布时间】:2015-03-13 12:22:34
【问题描述】:

我有单元格的自定义类,我有 UItableView 显示单元格的元素,例如标签和图像,我也使用 parse.com 作为应用程序的后端,每当我刷新表格时,最后一个单元格将重复第一个单元格,所以我一直在寻找解决方案以防止重复单元格,这是我的 cellForRowAtIndexPath 代码。

提前感谢您的帮助。

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
    }        

【问题讨论】:

    标签: ios uitableview swift parse-platform


    【解决方案1】:

    这段代码有两个问题:

    1) 由于单元格被缓存,因此您返回的最后一个单元格可能具有从前一个单元格配置的数据。这样做的结果是它将显示来自旧单元格的数据和图像。

    这可以通过将myCell.postedImage.image 初始化为nil 或某个占位符图像来解决。

    2) 您正在对缓存单元进行异步请求。这意味着当 `` 完成时,myCell 可以被重新用于另一行。因此,您现在将图像设置在不同的单元格上。这也会导致像您描述的那样令人困惑的结果。

    【讨论】:

    • 请问您能帮我解决这个问题吗?
    • 我已经在自定义类单元格中使用了准备重用,并使 myCell.postedImage.image = nil 问题仍然存在,任何帮助将不胜感激
    【解决方案2】:

    好的,经过几天的工作,我发现问题出在哪里并修复了它,它不是来自 cellForRowAtIndexPath 函数,而是来自与 parse 通信的代码,我添加了一个代码来防止重复单元格与所有元素属于单元格,因此我的代码看起来像这样

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-13
      • 1970-01-01
      • 2015-11-13
      • 1970-01-01
      • 1970-01-01
      • 2020-06-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多