【问题标题】:How to update Data in tableview using swift?如何使用swift更新tableview中的数据?
【发布时间】:2015-09-11 15:44:38
【问题描述】:

目前我有 3 个 swift 文件:ManualViewController、AutoViewController、Main

ManualViewController 是带有表格视图的 UIViewController。 AutoViewController 是一个带有几个按钮的 UIViewController。 Main 只是一个包含表格视图所有数据的 swift 文件。

ManualViewController 和 AutoViewController 使用 TabBarController 控制。

当我运行应用程序时,在 Main.swift 中找到的初始内容被加载到表视图中。当我转到下一个视图,即 AutoViewController 并单击一个按钮以更改 Main.swift 中的数据时,数据会更改。问题是当我切换回 ManualViewController 时,表格仍然包含旧数据,而不是更新后的数据。

我也试过这个:

override func viewWillAppear(animated: Bool) 
{
    super.viewWillAppear(false)
    self.tableView.reloadData()
}

还是不行。

【问题讨论】:

  • 我认为您没有更新用于在 ManualViewController 中显示的数组或数据。
  • 我确实更新了数据,我可以在 ManualViewController 中打印更新的数据,但不能在 tableview 中加载更新的数据。
  • Main.swift 中的内容是什么样的?它是一个对象吗?一个变量 ?一个结构?

标签: ios swift uitableview uitabbarcontroller


【解决方案1】:

一般情况下,UITableView中的数据更新方式是

self.tableView.reloadData()

【讨论】:

    【解决方案2】:

    您可以使用NSNotificationCenter 从另一个视图更新您的tableView。

    viewDidLoad 方法中的tableView 控制器中的-addObserver: 声明必须是这样的:

    override func viewDidLoad() {
        super.viewDidLoad()
         NSNotificationCenter.defaultCenter().addObserver(self, selector: "refreshTable:", name: "refresh", object: nil)
    }
    

    你的这个addObserver的函数会喜欢:

     func refreshTable(notification: NSNotification) {
    
        println("Received Notification")
        self.tableView.reloadData()
    }
    

    现在您可以在导航到 tableView 控制器时发布这样的通知:

    NSNotificationCenter.defaultCenter().postNotificationName("refresh", object: nil, userInfo: nil)
    

    查看THIS 示例项目了解更多信息。

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2019-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多