简体   繁体   English

防止在Swift中的可重用单元格上重新加载

[英]Prevent reloading on reusable cells in Swift

I am new to Swift language and I am facing a problem... 我是Swift语言的新手,现在遇到了问题...

In the "My profile" tableview, I query (to Parse) for all currentUser()'s posts with an includeKey of array of pointers that point to tagged objects from an other Class. 在“我的个人资料”表视图中,我使用指向包含另一个类的已标记对象的指针数组的includeKey来查询(以Parse)所有currentUser()的帖子。

For each post, I have to set different colors for each object that is tagged according to its "type" (using AttributedStrings to concatenated strings) 对于每个帖子,我必须为根据其“类型”标记的每个对象设置不同的颜色(使用AttributedStrings连接字符串)

I discovered that cells are reloading each time I scroll down but the thing is the code is becoming quite heavy and slow. 我发现每次向下滚动时都在重新加载单元格,但问题是代码变得非常繁琐和缓慢。

Do you have an idea how I could fix this or how I could prevent cells from being reused ? 您是否知道如何解决此问题或如何防止单元被重用?

Thanks a lot. 非常感谢。

This is my code from the cellForRowAtIndexPath() : 这是来自cellForRowAtIndexPath()的代码:

    cell.selectionStyle = UITableViewCellSelectionStyle.None

    // pour activer la selection de cellules
    // cell.selectionStyle = UITableViewCellSelectionStyleBlue;(By Default)
    // cell.selectionStyle = UITableViewCellSelectionStyleGray;

    var imageToLoad = self.images[indexPath.row] as PFFile
    var imageCaption = self.imageCaptions[indexPath.row] as String
    var imageDate = self.imageDates[indexPath.row] as String
    var postKooleqts: AnyObject = self.kooleqts[indexPath.row] as AnyObject

            imageToLoad.getDataInBackgroundWithBlock{(imageData, error) -> Void in
        if (error == nil){

            var finalizedImage = UIImage(data:imageData!)
            cell.postImage.image = finalizedImage

        }
    }

    cell.postCaption.text = imageCaption
    cell.postDate.text = imageDate
    cell.nbKooleqts.text = "\(postKooleqts)"

    var x = 0
     var htmlString = ""

        if (linkedPages[indexPath.row].count > 0){
        while x < linkedPages[indexPath.row].count {

            println("indexx : \([indexPath.row])")
            println("stringg : \(htmlString)")

            let pageToAdd = linkedPages[indexPath.row][x]["name"] as! String

            //let test = linkedPages[indexPath.row][x]

            //println("resultat \([indexPath.row]) : \([test])")

            if (linkedPages[indexPath.row][x]["type"] as! String == "obj"){
            stringToAdd = "<span style=\"font-family : HelveticaNeue; font-size : 15;  color: white;\"><span style=\"font-weight: bold; color: #c00b0b\">\(pageToAdd) </span>- -</span>"
            }
            else if (linkedPages[indexPath.row][x]["type"] as! String == "bra"){
            stringToAdd = "<span style=\"font-family : HelveticaNeue; font-size : 15;  color: white;\"><span style=\"font-weight: bold; color: #0099ff\">\(pageToAdd)</span>- -</span>"
            }
            else if (linkedPages[indexPath.row][x]["type"] as! String == "peo"){                let stringToAdd = "<span style=\"font-family : HelveticaNeue; font-size : 15; color: white;\"><span style=\"font-weight: bold; color: #0bdf6a\">\(pageToAdd)</span>- -</span>"
            }
            else if (linkedPages[indexPath.row][x]["type"] as! String == "eve"){
            stringToAdd = "<span style=\"font-family : HelveticaNeue; font-size : 15;  color: white;\"><span style=\"font-weight: bold; color: #cc99ff\">\(pageToAdd)</span>- -</span>"
            }
            else if (linkedPages[indexPath.row][x]["type"] as! String == "pla"){
            stringToAdd = "<span style=\"font-family : HelveticaNeue; font-size : 15;  color: white;\"><span style=\"font-weight: bold; color: #e16818\">\(pageToAdd)</span>- -</span>"
            } else {stringToAdd = ""}

            htmlString = htmlString + "\(stringToAdd)"

            var encodedData = htmlString.dataUsingEncoding(NSUTF8StringEncoding)!
            var attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
            let attributedString = NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil, error: nil)

            cell.linkedPages.attributedText = attributedString

            x++

            }

        }else {

            println("empty")

            cell.linkedPages.text = ""

    }

    return cell
}

UPDATE : The linkedPages seems to be the main lag issue as if I remove it, it no longer lags 更新 :链接的页面似乎是主要的滞后问题,好像我删除它,不再滞后

UPDATE2 : Here is the working code to have the before/after, no lags anymore : UPDATE2 :这是工作之前/之后的工作代码,不再滞后:

 var x = 0
     var htmlString = ""
    var attributedString = NSMutableAttributedString()

    var attrs:[String : AnyObject]?

        if (linkedPages[indexPath.row].count > 0){

        while x < linkedPages[indexPath.row].count {

            //println("indexx : \([indexPath.row])")
            //println("stringg : \(htmlString)")

            var pageToAdd = linkedPages[indexPath.row][x]["name"] as! String

            attributedString = NSMutableAttributedString(attributedString: attributedString)
            var addComma = NSMutableAttributedString(string: ", ")

            var paraStyle = NSMutableParagraphStyle()
            paraStyle.paragraphSpacing = 15.0

            if (linkedPages[indexPath.row][x]["type"] as! String == "obj"){
                attrs = [NSFontAttributeName : UIFont.boldSystemFontOfSize(15.0), NSForegroundColorAttributeName : UIColor(red: 192.0/255.0, green: 11.0/255.0, blue: 11.0/255.0, alpha: 1.0), NSParagraphStyleAttributeName : paraStyle]
            }
            else if (linkedPages[indexPath.row][x]["type"] as! String == "bra"){
                attrs = [NSFontAttributeName : UIFont.boldSystemFontOfSize(15.0), NSForegroundColorAttributeName : UIColor(red: 12.0/255.0, green: 153.0/255.0, blue: 255.0/255.0, alpha: 1.0), NSParagraphStyleAttributeName : paraStyle]
            }
            else if (linkedPages[indexPath.row][x]["type"] as! String == "peo"){
            attrs = [NSFontAttributeName : UIFont.boldSystemFontOfSize(15.0), NSForegroundColorAttributeName : UIColor(red: 11.0/255.0, green: 223.0/255.0, blue: 106.0/255.0, alpha: 1.0), NSParagraphStyleAttributeName : paraStyle]
            }
            else if (linkedPages[indexPath.row][x]["type"] as! String == "eve"){
            attrs = [NSFontAttributeName : UIFont.boldSystemFontOfSize(15.0), NSForegroundColorAttributeName : UIColor(red: 204.0/255.0, green: 153.0/255.0, blue: 255.0/255.0, alpha: 1.0), NSParagraphStyleAttributeName : paraStyle]
            }
            else if (linkedPages[indexPath.row][x]["type"] as! String == "pla"){
            attrs = [NSFontAttributeName : UIFont.boldSystemFontOfSize(15.0), NSForegroundColorAttributeName : UIColor(red: 225.0/255.0, green: 90.0/255.0, blue: 1.0/255.0, alpha: 1.0), NSParagraphStyleAttributeName : paraStyle]
            }


            var coloredString = NSMutableAttributedString(string:"\(pageToAdd)", attributes:attrs)

            attributedString.appendAttributedString(coloredString)
            attributedString.appendAttributedString(addComa)


            cell.linkedPages.attributedText = attributedString

            x++

            }

        }else {

            println("empty")

            cell.linkedPages.text = ""

    }

            return cell

The likely reason is your call to getData() for the images in each cell. 可能的原因是您为每个单元格中的图像调用了getData() As far as I know there is no way to not reuse cells, as that's exaclty what the method is designed to do. 据我所知,没有办法不重复使用单元格,因为这是该方法设计的目的。 The reason this is getting so slow is that the OS is trying to wait for each image to be loaded in order to display the cell, and doing this will bog it down very quickly. 之所以变得如此缓慢,是因为OS试图等待加载每个图像才能显示该单元,并且这样做会使它很快停顿下来。 Instead what you need to do is set a default image for the cell, and then call var imageData = imageToLoad.getDataInBackground({}) . 相反,您需要做的是为单元格设置默认图像,然后调用var imageData = imageToLoad.getDataInBackground({}) This will allow the cells to be returned while scrolling, and then the images will be populated after they've loaded instead of waiting to draw the cell until the image is retrieved. 这将允许在滚动时返回单元格,然后在图像加载后填充图像,而不是等待绘制单元格直至检索到图像。

Why don't you implement an image cache, instead of downloading every time the cell is created, check and see if you haven't already downloaded the image, and if you have use the previously downloaded copy. 为什么不实现图像缓存,而不是每次创建单元时都不下载,而是检查并查看是否还没有下载图像,以及是否使用了以前下载的副本。

You would have to tune the size of your cache to your memory requirements and eject images that are far away from your current position in the table. 您将必须根据内存需求调整缓存大小,并弹出与表中当前位置相距甚远的图像。

You code also has another issue in that if you scroll down really fast it will queue up lots and lots of downloads. 您的代码还存在另一个问题,如果您快速向下滚动,则会排队等待大量下载。 Ideally you need to either have a way to cancel downloads for cells that are no longer in view, or to stop the background downloads until the table stops scrolling. 理想情况下,您需要有一种方法可以取消不再显示的单元格的下载,或者停止后台下载,直到表格停止滚动为止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM