首页 > 解决方案 > 导入数据后如何重新加载 UITableView?

问题描述

我有一个 UITableView,它从应用程序的沙箱中获取数据,由 FileManager 的“.import”函数实现。基本上,我有一个“添加”按钮,可以弹出“UIDocumentPickerViewController”,我可以导入文件,UITableView 会显示它们。

我的问题是,当我导入文件时,它没有显示在 TableView 中,我必须退出应用程序并重新打开它才能显示文件。

我用“self.tableView.reloaddata()”和“tableView.reloaddata()”尝试了各种各样的东西,但没有任何效果,甚至没有出现在控制台中。我也尝试提供一个“刷新”按钮,但它也不起作用......

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        let dirPaths = FM.urls(for: .documentDirectory, in: .userDomainMask)
        let docsDir = dirPaths[0].path
        let importedfiles = try! FM.contentsOfDirectory(atPath: docsDir)


        self.importedfiles! = importedfiles as NSArray

    }


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return importedfiles.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

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

    cell.titleLabel.text = importedfiles[indexPath.row] as? String

    return 

更可取的是,当我导入文件时,TableView 会自行刷新。(按钮的东西只是一个测试)

标签: iosswiftxcodeuitableview

解决方案


选择新文档后,您需要重新加载数据。

class YourViewController: UIViewController {


  ...

  override func viewDidLoad() {
    super.viewDidLoad()
    self.loadFiles();
  }

  func loadFiles() {
    let dirPaths = FM.urls(for: .documentDirectory, in: .userDomainMask)
    let docsDir = dirPaths[0].path
    let importedfiles = try! FM.contentsOfDirectory(atPath: docsDir)

    self.importedfiles! = importedfiles as NSArray
  }


  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return importedfiles.count
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

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

    cell.titleLabel.text = importedfiles[indexPath.row] as? String

    return cell;
  }

  ....
}


extension YourViewController: UIDocumentPickerDelegate {
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
      self.loadFiles();
      self.tableView.reloadData();
    }
}

推荐阅读