SDWebImage中的cellForRowAtIndexPath中的图像设置不正确

时间:2015-02-25 14:26:52

标签: ios objective-c uitableview swift sdwebimage

我正在使用SDWebImage, 我创建的下载进度效果与WhatsApp应用程序相同。

问题在于,当我滚动tableView时,它显示了不正确的单元格图像。(即:当重复使用单元格时,随机图像在单元格中设置。)

这是我在Swift中的代码:

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

    var cell:ImageCellTableViewCell = self.IBtblImageTable.dequeueReusableCellWithIdentifier("ImageCell", forIndexPath: indexPath) as ImageCellTableViewCell
    var url:NSURL = NSURL(string: imageArray[indexPath.row])!
    cell.tag = indexPath.row
    manager?.downloadImageWithURL(url, options: SDWebImageOptions.ProgressiveDownload, progress: { (recievedSize:Int, expectedSize:Int) -> Void in

        if(recievedSize>0){

            var progress:Float = 0

            progress = Float(recievedSize)/Float(expectedSize)

            println(CGFloat(progress))


        }else{}

    }, completed: { (image:UIImage!, error:NSError!, cacheType:SDImageCacheType, finished:Bool, url:NSURL!) -> Void in


        if ((image) != nil && cell.tag == indexPath.row)
        {
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                cell.IBimgCellImage.image = image
            })

        }


    })

    return cell
}

1 个答案:

答案 0 :(得分:2)

声明字典:

var progressDic: [String:CGFloat] = [:]

然后,

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

var cell:ImageCellTableViewCell = self.IBtblImageTable.dequeueReusableCellWithIdentifier("ImageCell", forIndexPath: indexPath) as ImageCellTableViewCell
var url:NSURL = NSURL(string: imageArray[indexPath.row])!
var progressCircle :CAShapeLayer?
cell.IBimgCellImage.layer.sublayers = nil
cell.IBimgCellImage.image = nil

if(progressCircle == nil && progressDic[String(indexPath.row)] != 1.0){
    progressCircle = getProgressCircleLayer(cell.IBimgCellImage.center)
    cell.IBimgCellImage.layer.addSublayer(progressCircle)
    }

manager?.downloadImageWithURL(url, options: SDWebImageOptions.ProgressiveDownload, progress: { (recievedSize:Int, expectedSize:Int) -> Void in
    var progress:Float?

    if(recievedSize>0){
        progress = Float(recievedSize)/Float(expectedSize)
       self.progressDic.updateValue(CGFloat(progress!), forKey: String(indexPath.row))
            progressCircle?.strokeEnd = self.progressDic[String(indexPath.row)]!


    }else{}

}, completed: { (image:UIImage!, error:NSError!, cacheType:SDImageCacheType, finished:Bool, url:NSURL!) -> Void in


   dispatch_async(dispatch_get_main_queue(), { () -> Void in

                if (tableView.indexPathForCell(cell)?.row == indexPath.row)
                {
                cell.IBimgCellImage.image = image
                }
            })

    })

return cell
}

就是这样。