My data changes in UITableViewCell when I scroll down and get back

浪尽此生 提交于 2020-01-10 19:59:42

问题


When I'm populating new data in my tableView Controller, my top cell is being rewrite by the bottom one. Let me explain. I have one image that is loading async in the latest cell row, in the bottom. All the other cells are loading static with an image that is in the app. When I scroll down my app and display my bottom cell which have a different image than the others cells, and I scroll up again, I see the first shop image has changed to the dynamic one loaded in the bottom cell. Does anyone know why this is happening?

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell : shopsTableViewCell = tableView.dequeueReusableCellWithIdentifier("shopCell", forIndexPath: indexPath) as! shopsTableViewCell

    cell.index = indexPath.row
    let qualityOfServiceClass = QOS_CLASS_BACKGROUND
    let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
    let apiCall = webApi()


        dispatch_async(backgroundQueue, {
            apiCall.downloadPhotoAsync("http://api-ytyg.wbbdev.com/files/shops/\(shops[indexPath.row].id)/\(shops[indexPath.row].featured_img)"){(image: UIImage?) -> Void in
                dispatch_async(dispatch_get_main_queue()){
                    if(image != nil){
                        if (cell.index == indexPath.row){
    //                            shops[indexPath.row].photo = image!
                            cell.shopImg?.image = image
                        }

                    }else{
                        shops[indexPath.row].photo = UIImage.init(named: "No_Image_Available.jpg")!
                    }
                }
            }
        })
    cell.shopName?.text = shops[indexPath.row].name
    cell.shopDescription?.text = shops[indexPath.row].address

    cell.label1?.text = shops[indexPath.row].city + " | " + shops[indexPath.row].distance + "Km"
    cell.becomeFirstResponder()
    return cell
}


回答1:


it is because your cells are being reused :

// this line initialize a cell of type shopsTableViewCell 
//if no cell can be reused, get an already used cell else
let cell : shopsTableViewCell 
                 = tableView.dequeueReusableCellWithIdentifier("shopCell",
                                  forIndexPath: indexPath) as! shopsTableViewCell

so image and other data should be the last image and data of the dequeued cell.

To avoid this, you shall implement prepareForReuse in the cell class file to reset data and image. docs of apple about prepareForReuse func

From Apple docs :

If a UITableViewCell object is reusable—that is, it has a reuse identifier—this method is invoked just before the object is returned from the UITableView method dequeueReusableCellWithIdentifier:. For performance reasons, you should only reset attributes of the cell that are not related to content, for example, alpha, editing, and selection state. The table view's delegate in tableView:cellForRowAtIndexPath: should always reset all content when reusing a cell. If the cell object does not have an associated reuse identifier, this method is not called. If you override this method, you must be sure to invoke the superclass implementation.

 //Example :
 override func prepareForReuse() {
    super.prepareForReuse()
    //Do reset here
    this.shopImg?.image = nil
    this.shopName?.text = ""
    this.shopDescription?.text = ""

}



回答2:


I think the issue is that while you are scrolling, your images are still in downloading process (that's why you have a nil on that particular line of code). So you have to wait for it.

I am guessing that you have an array of images. If you don't, then you must make one. You must use it like so:

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return arrayThatcontainsShopImages.count
}

Note: that every time you add downloaded image to this array, you should call tableView.reloadData()

Using SDWebImage can be far superior. Look at the following code using this library, you just create an instance of UIImageView. then using this library, you can download image directy to imageview instance, and to access the image, you can use imageView.image property of UIImageView class

 let imageView = UIImageView()
 imageView.sd_setImageWithURL(someURL, placeholderImage: UIImage())
 self.arrayOfImageViews.append(imageView)


来源:https://stackoverflow.com/questions/38131981/my-data-changes-in-uitableviewcell-when-i-scroll-down-and-get-back

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!