gpt4 book ai didi

ios - 在 TableViewCell Swift 中从 Firebase 加载图像

转载 作者:行者123 更新时间:2023-11-28 15:09:10 25 4
gpt4 key购买 nike

我正在尝试从我的 Firebase 数据库加载图像到我的 TableView 单元格中。我正在使用 AlamofireImage。

@IBOutlet weak var tableView: UITableView!

var storiesArray = [Stories]()

override func viewDidLoad() {
super.viewDidLoad()

retrieveStories()
}

我在 viewDidLoad() 调用的函数中获取 imageDownloadURL

 func retrieveStories() {

let storiesDB = Database.database().reference().child("storyDetails")

storiesDB.observe(.childAdded) { (snapshot) in

let snapshotValue = snapshot.value as! Dictionary<String,String>
let autor = snapshotValue["autor"]!
let genre = snapshotValue["genre"]!
let titel = snapshotValue["titel"]!
let downloadURL = snapshotValue["imageDownloadURL"]


let story = Stories()
story.genre = genre
story.titel = titel
story.autor = autor
story.downloadURL = downloadURL

self.storiesArray.append(story)

DispatchQueue.main.async(execute: {
self.tableView.reloadData()
})

}
}

在我获得所有这些数据后,我想从我现在在 storiesArray.downloadURL 中的 url 下载图像

我在 cellForRowAtIndexPath 中这样做

let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! StoryDetailCell

if storiesArray[indexPath.row].downloadURL != nil {
Alamofire.request(indexPathRow.downloadURL!).responseImage { response in
debugPrint(response)

print(response.request as Any)
print(response.response as Any)
debugPrint(response.result)

if let image = response.result.value {
print("image downloaded: \(image)")
DispatchQueue.main.async {
cell.storyImage.image = image
}

}
}
} else if indexPathRow.downloadURL == nil {
cell.storyImage.image = #imageLiteral(resourceName: "standard")
}

只有当前显示单元格时才会加载图像。这会导致很多问题。一个问题是,如果我滚动的速度快于图像加载的速度,它将显示在另一个单元格中。

我想知道如何处理这种情况。

最佳答案

let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! StoryDetailCell

cell.storyImage.image = nil

cell.tag += 1
let tag = cell.tag

if storiesArray[indexPath.row].downloadURL != nil {
Alamofire.request(indexPathRow.downloadURL!).responseImage { response in

if let image = response.result.value {
if cell.tag == tag {
DispatchQueue.main.async {
cell.storyImage.image = image
}
}
}
}
} else if indexPathRow.downloadURL == nil {
cell.storyImage.image = #imageLiteral(resourceName: "standard")
}

关于ios - 在 TableViewCell Swift 中从 Firebase 加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47947739/

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