gpt4 book ai didi

ios - 从模拟器中的 firebase 加载图像后,图像不断变化

转载 作者:行者123 更新时间:2023-11-28 23:55:59 24 4
gpt4 key购买 nike

我有一个跟随 View Controller ,其中嵌入了一个 TableView Controller 。当我尝试从 firebase 加载个人资料图像时,它加载得很好,但在向下或向上滚动时不断与其余个人资料图像交换图像。此外,当我点击表格 View 单元格以关注该特定用户时,指示(复选标记)也会出现在第四个单元格上。这是 xcode 中的错误吗我在 Mac os Sierra 10.12.6 上使用 Xcode 9.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()
}

关于ios - 从模拟器中的 firebase 加载图像后,图像不断变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51257328/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com