单选上多行上的Swift TableView ProgressView指示器

时间:2017-03-20 17:44:19

标签: swift tableview

我有一个tableview列表,其中包含一个select操作。当用户选择该行时,它会给出提示并开始下载文件并使用渐进式指示器显示进度。出于某种原因,指标每隔12条记录显示一次。为什么会发生这种情况......我是否错误地选择了这个细胞?

这是我的代码:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = self.tableView.cellForRow(at: indexPath) as! downloadCell
    let cellName = CurrentFiles[indexPath.row].labelName
    let internalName = CurrentFiles[indexPath.row].internalName
    let fileLocation = CurrentFiles[indexPath.row].fileName
    let safeURL = fileLocation.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
    let fileExtension = CurrentFiles[indexPath.row].fileExtension
    let fileDate = CurrentFiles[indexPath.row].lastUpdate
    if (cell.progressView.isHidden) && (cell.fileStatus == "Installed") && (cell.fileIcon.image ==  nil) {
        let fileLoc = getSharedFilePath(appGroup:applicationGroup,sharedFilename:"\(internalName).\(fileExtension)")
        let defaults = UserDefaults.standard
        defaults.set(fileLoc, forKey: "loadmap")
        defaults.set(cellName, forKey: "loadmapName")
        performSegue(withIdentifier: "gotoMap", sender: self)
    } else if (cell.progressView.isHidden) {
        alertControllerMsg(msgStyle: UIAlertControllerStyle.alert,msgTitle: "Download File", msgBody: "Are you sure you want to download \(cellName)?", cancelLbl: "Cancel", actionLbl: "Download", complete: {
            cell.fileStatus = "Installed"      //prevent double download
            //download file
            let destination: (URL, HTTPURLResponse) -> (URL, DownloadRequest.DownloadOptions) = {
                (temporaryURL, response) in
                if let directoryURL = FileManager().containerURL(forSecurityApplicationGroupIdentifier: applicationGroup), let suggestedFilename = response.suggestedFilename {
                    let filePath = directoryURL.appendingPathComponent("\(suggestedFilename)")
                    return (filePath, [.removePreviousFile, .createIntermediateDirectories])
                }
                return (temporaryURL, [.removePreviousFile, .createIntermediateDirectories])
            }
            if self.reachability.isReachableViaWiFi {
                cell.progressView.isHidden = false
                //BackendAPI is used to allow for downloads in background
                BackendAPIManager.sharedInstance.alamoFireManager.download(safeURL!, to: destination)
                    .downloadProgress { progress in
                        cell.fileIcon.image =  nil
                        cell.progressView.setProgress(Float(progress.fractionCompleted), animated: true)
                        cell.pctLabel.text = "\(String(format:"%g",round(progress.fractionCompleted*100)))%"
                    }.response { response in
                        cell.pctLabel.text = nil
                        cell.progressView.isHidden = true
                        cell.additionalLbl.text = nil
                        UserDefaults(suiteName: applicationGroup)!.set(fileDate, forKey: internalName)
                        cell.fileStatus = "Installed"
                        self.getAvailSpace()
                }
            } else {
                self.alertControllerMsg(msgStyle: UIAlertControllerStyle.alert,msgTitle: "Insufficient Network", msgBody: "Please connect to a Wifi network to download this file.", cancelLbl: "Cancel", actionLbl: "Retry", complete: {
                    self.downloadAndSort()
                })
            }
        })
    }
}

编辑:

CellforRowAt代码

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if let cell = tableView.dequeueReusableCell(withIdentifier: "downloadCell", for: indexPath) as? downloadCell {
        let currentFile = CurrentFiles[indexPath.row]
        cell.configureCell(currentFile: currentFile)
        return cell
    } else {
        return downloadCell()
    }
}

编辑2:

class downloadCell: UITableViewCell {

@IBOutlet weak var fileLbl: UILabel!
@IBOutlet weak var fileIcon: UIImageView!
@IBOutlet weak var pctLabel: UILabel!
@IBOutlet weak var additionalLbl: UILabel!
@IBOutlet weak var fileSize: UILabel!
@IBOutlet weak var progressView: UIProgressView!

var fileStatus = "NotInstalled"
func configureCell(currentFile: currentFiles) {

    fileLbl.text = currentFile.labelName
    fileSize.text = currentFile.fileSize
    let internalName = currentFile.internalName
    fileIcon.image = UIImage(named: "download")
    additionalLbl.text = "Updated: \(convertDateFormatter(date: currentFile.lastUpdate))"

    let fileExists = (readFromSharedFile(sharedFilename: internalName, fileExtension: currentFile.fileExtension))
    if fileExists == "Success" {
        //file has been downloaded on device
        let lastUpdateDate = UserDefaults(suiteName: applicationGroup)!.string(forKey: internalName)

        if lastUpdateDate != currentFile.lastUpdate {
                fileIcon.image =  UIImage(named: "download")
                fileStatus = "NeedsUpdate"
            } else {
                fileIcon.image = nil
                fileStatus = "Installed"
                additionalLbl.text = nil
            }
    } else {
        // not on device
        fileStatus = "NotInstalled"

    }
}
}

4 个答案:

答案 0 :(得分:1)

在我的视图控制器上,我创建了一个新字典来保存我的文件名和当前进度默认为0以及一个数组来保存当前正在下载的文件

var downloadProg = [String: Double]()
var currentDownloadNames = [String]()

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if let cell = tableView.dequeueReusableCell(withIdentifier: "downloadCell", for: indexPath) as? downloadCell {
        let currentFile = CurrentFiles[indexPath.row]
        cell.configureCell(currentFile: currentFile)
        if !(currentDownloadNames.contains(currentFile.labelName)) {
            cell.progressView.isHidden = true
            cell.pctLabel.isHidden = true
            cell.fileIcon.isHidden = false
        } else {
            cell.fileIcon.isHidden = true
            cell.progressView.isHidden = false
            cell.pctLabel.isHidden = false
        }
        return cell
    } else {
        return downloadCell()
    }
}

我现在在.downloadProgress中设置字典百分比

                            downloadProg[cellName] = progress.fractionCompleted

我修改了downloadCell以显示百分比:

let pct = downloadProg[currentFile.labelName]
    if (progressView.isHidden == false){
        progressView.setProgress(Float(pct!), animated: true)
        pctLabel.text = "\(String(format:"%g",round(pct!*100)))%"
    } 

答案 1 :(得分:0)

我们确实需要cellForRowAtindex的代码以及对问题的更好描述。有多少个细胞适合屏幕(是12左右)?是仅显示每个第12个单元格的进度视图还是在每12个单元格中运行实际进度?如果进度视图刚刚显示但未更新,那么最明显的原因是您忘记在progressView中隐藏cellForRowAtindexdequeue​Reusable​Cell(with​Identifier:​)在{{1}之后重新使用单元格时}}

答案 2 :(得分:0)

在检查器构建器中将cell.progressview hidden标志勾选为true。或者您必须打印并检查隐藏状态以获取进度视图。

答案 3 :(得分:0)

听起来您需要在prepareForReuse中重置进度视图:

在单元格覆盖中:

override func prepareForReuse() {

}

当重复使用单元格时会调用它,这听起来像是为自己发生的事情。