当UITableView单元格中的进度条还不可见时,如何更新进度条



我遇到了一个问题:我有一个表视图,在其中我显示了云存储中用户文件的列表。我已经成功地通过点击位于单元格上的按钮将这些文件下载到设备上。单击后,单元格上会显示一个进度条,其中显示文件下载的进度。现在,我需要通过单击"全部下载"按钮来实现下载所有文件的功能。但我遇到了一个问题:我可以一起下载所有文件,但无法在表视图之外的单元格中显示下载进度。我希望进度条显示当前进度,即使单元格不可见。当我向下滚动"表视图"时,当出现一个新单元格时,我可以看到当前的加载进度。我该怎么做?我试过很多种选择,但没有一种是正确的。下面你可以看到我现在的代码:

class SourceFileListViewController: UIViewController {
private var isDownloadAllButtonPressed: Bool = false
private var cellsWithFilesIndexPathes: [IndexPath] = []
private var currentProgress: [IndexPath : Double] = [:]
...
@objc private func barButtonAction() {
isDownloadAllButtonPressed = true
for indexPath in cellsWithFilesIndexPathes {
fileListSource?.downloadFile(path: fileListSource?.files[indexPath.row].path,
pathComponent: fileListSource?.files[indexPath.row].name,
completion: { progress in
self.currentProgress[indexPath] = progress

}, callback: {
self.getTrackNames {
self.tableView.reloadRows(at: [indexPath], with: .automatic)
}
})
}
}
extension SourceFileListViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: SourceFileListCell.reuseId,
for: indexPath) as! SourceFileListCell
cell.progressBar.isHidden = true
cell.delegate = self
cell.progressBar.setProgress(to: 0)
....
//Here I check the file this or folder
let entry = fileListSource?.unreformedFileList[indexPath.row]
switch entry {
case _ as Files.FileMetadata:
cell.downloadButton.isHidden = false
cell.artworkImageView.image = UIImage(systemName: "music.note")
//If this is a file, I put its indexPath in an array so that it can be downloaded by the Download All button
cellsWithFilesIndexPathes.append(indexPath)
if isDownloadAllButtonPressed {
cell.progressBar.isHidden = false
guard let progress = currentProgress[indexPath] else { return cell }
cell.progressBar.setProgress(to: progress)
}
case _ as Files.FolderMetadata:
cell.downloadButton.isHidden = true
cell.artworkImageView.image = UIImage(systemName: "folder.fill")
default:
break
}

//Here I check if there is such a file in the user library
guard let fileName = fileListSource?.files[indexPath.row].name else { return cell }
if trackNames.contains(fileName) {
cell.downloadButton.setImage(UIImage(systemName: "checkmark.circle.fill"), for: .normal)
} else {
cell.downloadButton.setImage(UIImage(systemName: "icloud.and.arrow.down"), for: .normal)
}

return cell

}
}

您的数据源需要存储当前进度,以便您可以在cellForRowAt:IndexPath:中调用cell.progressBar.setProgress

您可以使用显示的项目数初始化数组,所有项目的初始值均为0,并在downloadFile完成块中使用新进度更新indexPath.row处的数组。

最新更新