我有一个跟随视图控制器,其中嵌入了一个表格视图控制器。 当我尝试从Firebase加载配置文件图像时,它加载得很好,但在向下或向上滚动时,它会与其余的配置文件图像保持互换状态。 同样,当我点击表格视图单元格以跟随该特定用户时,指示(复选标记)也会出现在第四个单元格上。 这是xcode中的错误吗 我在Mac OS Sierra 10.12.6上使用Xcode 9.1
答案 0 :(得分:1)
如果要从背景获取图像,请确保将每个图像分配给正确的单元格。一种实现方法是创建一个包含图像和唯一ID的自定义类,每当您要将图像分配给单元格时,请先检查ID以确保其正确。
关于复选标记错误,您可以尝试重置prepareForReuse()
函数中的单元格。
编辑
由于您正在使用异步,因此无法保证将按顺序返回图像。因此,要将正确的图像放入正确的单元格中,您需要执行以下操作
//if the image is already fetched, you don't have to get it from firebase again
private var imageCache = [String:UIImage]()
//Create custom ImageView class that downloads image from url
class CustomImageView: UIImageView{
var lastImageURL: String?
//call this function to get the right image with url
func setupWithImageURL(imageURL: String){
self.contentMode = .scaleAspectFill
self.clipsToBounds = true
//keep track of the url of the right image
lastImageURL = imageURL
//check if the image is already there
if let cachedImage = imageCache[imageURL]{
self.image = cachedImage
return
}
//if no image, get it with url
guard let url = URL(string: imageURL) else {return}
URLSession.shared.dataTask(with: url) { (data, response, err) in
if let err = err{
print("Unable to download data from database: ",err)
return
}
guard let data = data else {return}
guard let image = UIImage(data: data) else {return}
imageCache[url.absoluteString] = image
//if not the correct image, return and do nothing
if (url.absoluteString != self.lastImageURL){
return
}
//if the image is the correct one, set it to the imageView
DispatchQueue.main.async {
self.image = image
}
}.resume()
}
}