【问题标题】:How to reload UITableView after importing data?导入数据后如何重新加载 UITableView?
【发布时间】:2019-05-29 16:27:36
【问题描述】:

我有一个 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 会自行刷新。 (按钮的东西只是一个测试)

【问题讨论】:

  • tableView.datasource 已设置?
  • 不要使用NSArray。使用合适的 Swift 数组。
  • 多亏了你们两位,我没有设置数据源,我对此感到非常愚蠢!另外,为什么使用 Array 而不是 NSArray?我更改了它,但不知道为什么会出现问题...

标签: ios swift xcode uitableview


【解决方案1】:

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

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();
    }
}

【讨论】:

  • 确保设置 UIDocumentPickerDelegate: yourDocumentPicker.delegate = self
  • 谢谢!第一次在这里问问题,我并不失望!非常感谢!
猜你喜欢
  • 1970-01-01
  • 2023-03-31
  • 2013-11-13
  • 2013-06-25
  • 2013-02-18
  • 2013-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多