滚动时,tableview单元格中的图像会发生变化

时间:2016-08-24 07:23:56

标签: ios iphone swift

我在UITableviewcell时出现问题,当我滚动时图像不断变化,有些时候将错误的图像设置为单元格!

 let request = NSURLRequest(URL: url)
    cell.img.contentMode = .ScaleAspectFit

    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
            (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in

        if(error != nil){
            print(error)
        }

        if let imageData = data as NSData? , let image = UIImage(data: imageData) where imageData.length != 0 {
            cell.img.image = image
            cell.img.contentMode = contentMode
            return;
        }

        let cachedResponse = NSURLCache.sharedURLCache().cachedResponseForRequest(request)
        if let cachedResponse = cachedResponse , let image = UIImage(data: (cachedResponse.data)){
            cell.img.image = image;
            cell.img.contentMode = contentMode
        }

    }


显示案例的gif:

http://im2.ezgif.com/tmp/ezgif-2265120982.gif


注意:
我在stackoverflow中搜索我发现问题和答案但是对我来说没有问题之一:
Wrong image is set in my tableview cell sometimes when I scroll on my tableview. How can I fix this?

1 个答案:

答案 0 :(得分:0)

在自定义UITableviewcell中,您需要实施prepareForReuse方法并将图片设置为零值

override func prepareForReuse() {
    img.image = nil   
}