swift - 错误的图像加载到 TableView

标签 swift uitableview nscache

这是我第一次将 NSCache 用于 TableView 。对于 cellForRow,我调用 NSCache 来加载图像。图像有时是错误的图像。我可以做什么来解决这个问题?如果缓存不包含它,我会将照片替换为“randomguy”。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MyMessagesTableViewCell", for: indexPath) as! MyMessagesTableViewCell
    if let cachedImage = cache.object(forKey: urlArray[indexPath.row] as NSString) as? UIImage {
        cell.proPicImageView.image = cachedImage
        cell.proPicImageView.layer.cornerRadius =
        cell.proPicImageView.frame.size.height / 2
        cell.proPicImageView.layer.masksToBounds = true
        cell.proPicImageView.layer.borderWidth = 0
        cell.usernameLabel.text = usernameArray[indexPath.row]
        cell.messageLabel.text = messageArray[indexPath.row]
        cell.messageLabel.textColor = colorArray[indexPath.row]
        cell.messageLabel.font = fontArray[indexPath.row]
        cell.timeLabel.text = timeArray[indexPath.row]
    } else {
        cell.proPicImageView.image = UIImage(named: "randomguy")
        cell.proPicImageView.layer.cornerRadius =
        cell.proPicImageView.frame.size.height / 2
        cell.proPicImageView.layer.masksToBounds = true
        cell.proPicImageView.layer.borderWidth = 0
        cell.usernameLabel.text = usernameArray[indexPath.row]
        cell.messageLabel.text = messageArray[indexPath.row]
        cell.messageLabel.textColor = colorArray[indexPath.row]
        cell.messageLabel.font = fontArray[indexPath.row]
        cell.timeLabel.text = timeArray[indexPath.row]
    }

    return cell
}

在 View 中加载: 让缓存 = NSCache()

    func photoQuery () {
    for username in self.usernameArray {
        let photoQuery = PFQuery(className: "UserPhoto")
        photoQuery.whereKey("username", equalTo: username)
        photoQuery.findObjectsInBackground(block: { (objects: 
        [PFObject]?,error: Error?) in
        if let objects = objects {
            for object in objects {
                if error == nil {
                let userImageFile = object["photo"] as? PFFileObject
                let urlString = userImageFile?.url as! String

                    if let url = URL(string: urlString) {
                        let data = try? Data(contentsOf: url)
                        if let imageData = data {
            self.messageImageArray.append(UIImage(data:imageData)!)
            self.cache.setObject(UIImage(data:imageData)!, forKey: urlString as 
            NSString)
            self.urlArray.append(urlString as NSString)
            print(self.messageImageArray)
                        }
                    }
            }
        }

            }
        })
    }
}

最佳答案

这可以是您创建自定义 ImageView 并在其中包含一个函数的一种方法,该函数将负责下载图像并将图像分配给正确的单元格

let cache = NSCache<NSString, UIImage>()

class CustomImageView: UIImageView {
    var imageURLString: String?

    func startImageDownloadOperation(url: URL) {
        imageURLString = url.absoluteString

        if let cachedVersion = cache.object(forKey: url.absoluteString as NSString) {
            self.image = cachedVersion
        } else {
            let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
                guard error == nil,
                    let response = response as? HTTPURLResponse,
                    response.statusCode == 200 else {
                        DispatchQueue.main.async {
                            self.image = UIImage(named: "default")
                        }
                        return
                }

                DispatchQueue.main.async {
                    if let data = data {
                        let imageToCache = UIImage(data: data)
                        if url.absoluteString == self.imageURLString {
                            self.image = imageToCache
                            cache.setObject(imageToCache!, forKey: url.absoluteString as NSString)
                        }
                    }
                }
            }

            task.resume()
        }
    }
}

关于swift - 错误的图像加载到 TableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58739842/

相关文章:

swift - 如何点击屏幕上不可见的 CollectionView 单元格内的按钮

swift - 在 Core Data 中创建计算属性

ios - 在 SpriteKit 中触摸移动的 Sprite

ios - 带有 xib 的 UITableViewCell

objective-c - 如何在 Objective-C 中缓存图像

ios - 检查 iOS 上的 NSCache 内容?

swift - 自调整大小 Collection View 单元格大小问题

ios - [UITableView _endCellAnimationsWithContext :],/BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit/UIKit-3512.60.7/UITableView.m:1716

ios - 如何将表格 View 单元格中的字体颜色更改为变量 UIColor?

ios - 将 URL 设置为 NSCache 的键不起作用