繁体   English   中英

第二次加载viewcontroller时,UITableView reloadData无法正常工作

[英]UITableView reloadData not working when viewcontroller is loaded a 2nd time

我有一个带有自定义单元格的UITableView,显示可以下载的文件列表。 单元格显示文件名和下载状态。 一切正常,除了一个场景:

  1. 当文件正在下载时,用户下载文件并导航回主屏幕...
  2. 他回到了上一个屏幕。 文件下载仍在进行中。
  3. 文件下载完成。 我此时使用tableview.reloadData()将下载状态刷新为“Download Complete”,但reloadData()在此方案中不起作用。 单元格标签仍显示“正在下载”。

滚动tableview以使单元格退出屏幕并返回正确刷新单元格。 无论如何以编程方式执行此操作?“

否则,在用户不更改屏幕的正常情况下,reloadData()工作正常。

知道如何解决这个问题吗?

谢谢

我已经在下面的函数中使用了alamofire下载,该函数位于我的UIViewController中。

func DownloadFile(fileurl: String, indexPath: NSIndexPath, itemPath: String, itemName: String, itemPos: String, ItemSelected:Bool) {

      let cell = myTableView.cellForRowAtIndexPath(indexPath) as! myCustomCell

      let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)


        Alamofire.download(.GET, fileurl, destination: destination)


       .progress {bytesRead, totalBytesRead, totalBytesExpectedToRead in


            // This closure is NOT called on the main queue for performance
            // reasons. To update your ui, dispatch to the main queue.
            dispatch_async(dispatch_get_main_queue()) {
                print("Total bytes read on main queue: \(totalBytesRead) / \(totalBytesExpectedToRead)")


                let progress = Int((Double(totalBytesRead)/Double(totalBytesExpectedToRead)) * 100)


                cell.lblMoreRuqyaFileInfo.text = "Downloading file...(\(progress)%)"


            }
        }
         .response { _, _, _, error in

           if let error = error {
                print("\(error)")
                cell.lblMoreRuqyaFileInfo.text = "Failed to download file. Please try again."
            } else {


            cell.lblMoreRuqyaFileInfo.text = "File Downloaded sucessfully"

          //reloadData() not working from here
            self.myTableView.reloadData()

            }

    }

}

上面的func是在tableview的editActionsForRowAtIndexPath中调用的。

func tableView(tableView:UITableView,editActionsForRowAtIndexPath indexPath:NSIndexPath) - > [UITableViewRowAction]? {

    if myTableView.cellForRowAtIndexPath(indexPath) == nil {
        let action = UITableViewRowAction()
          return [action]

    }

    let cell = myTableView.cellForRowAtIndexPath(indexPath) as! myCustomCell

    let fileurl = cell.textLabel!.text
    let ruqyainfo = cell.lblMoreRuqyaFileInfo.text

    let sItemPath = cell.lblCompiledRuqya.text! + "->" + cell.textLabel!.text! + "->\(indexPath.section)->\(indexPath.row)"
    let sItemName = cell.lblCompiledRuqya.text!
    let sItemPos = "->\(indexPath.section)->\(indexPath.row)"
    var bItemSelected:Bool = false
    if myTableView.cellForRowAtIndexPath(indexPath)?.accessoryType == UITableViewCellAccessoryType.Checkmark {
        bItemSelected = true
    } else {

        bItemSelected = false
    }

     //check if file already downloaded,return empty action, else show Download button
    if ruqyainfo?.containsString("Download") == false {
        let action = UITableViewRowAction()
         return [action]

    }


    let line = AppDelegate.dictCompiledRuqya.mutableArrayValueForKey(AppDelegate.dictCompiledRuqya.allKeys[indexPath.section] as! String)

    let name = line[indexPath.row].componentsSeparatedByString("#")

    let DownloadAction = UITableViewRowAction(style: .Normal, title: "Download\n(\(name[3]))") { (action: UITableViewRowAction!, indexPath) -> Void in

            self.myTableView.editing = false

            AppDelegate.arrDownloadInProgressItem.append(name[0])

            self.DownloadFile(fileurl!, indexPath: indexPath, itemPath: sItemPath, itemName: sItemName,itemPos: sItemPos, ItemSelected: bItemSelected)

        }

    DownloadAction.backgroundColor = UIColor.purpleColor()
    return [DownloadAction]
}
//Objective C
    -(void)viewWillAppear:(BOOL)animated{
        [super viewWillAppear:animated];
       [self.yourTableView reloadData];
    }

//Swift
override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    self.yourTableView.reloadData()
}

您可以使用委托,以便下载控制器可以告诉第一个控制器下载完成,并且它应该重绘tableView - 或者至少是刚刚完成的indexPath。

像这样设置下载控制器

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
    let destinationController : DownloadController = segue.destinationViewController as! DownloadController
    destinationController.delegate = self

    destinationController.indexRowToRefresh = currentlySelectedIndexRow        
}

然后在下载完成闭包中添加这样的内容

   delegate.refreshTableRow(indexRowToRefresh)

并在您的第一个控制器中,实现委托方法来刷新此行(或整个表)

func refreshTableRow(indexRowToRefresh : Int)
{
    var indexPath = NSIndexPath(forRow: indexRowToRefresh, inSection: 0)
    tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Top)
}

嘿@John确保您的TableView数据源永久反映在文件上载状态中。

我认为,当您完成文件上传时,您将更改tableview数据源中的状态

1.当您切换到第二个视图控制器并返回上一个视图时,第一个场景可能是重新初始化您的数据源。 数据源可能未被永久反映。
2.在正常情况下,因为您在同一视图控制器上(不切换到其他视图控制器)。 Tableview数据源可能未重新初始化,保持更新的文件上载状态。

我建议保存在某些持久存储或Web服务器上保存的用户文件下载状态。 这不会导致数据不一致。

它可能是与线程相关的问题(也就是说你从下载线程回来,而不是在UI线程上,因此数据被刷新但不显示)。

尝试在self上使用它并传递一个刷新tableview的选择器。

performSelectorOnMainThread:

你用过:

let cell = myTableView.cellForRowAtIndexPath(indexPath) as! myCustomCell

并为lblMoreRuqyaFileInfo设置文本:

cell.lblMoreRuqyaFileInfo.text = "File Downloaded sucessfully"

所以,你不必调用self.myTableView.reloadData()
尝试:

dispatch_async(dispatch_get_main_queue()) {
        cell.lblMoreRuqyaFileInfo.text = "File Downloaded sucessfully"
    }

p / s你在哪里调用函数DownloadFile ,显示它,PLZ!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM