如何使用 swift 更新表视图中的数据?

How to update Data in tableview using swift?

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

ManualViewController 是具有 table 视图的 UIViewController。 AutoViewController 是一个带有几个按钮的 UIViewController。 Main 只是一个 swift 文件,其中包含 table 视图的所有数据。

ManualViewController 和 AutoViewController 是使用 TabBarController 控制的。

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

我也试过这个:

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

还是不行

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

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

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 控制器时,您可以 post 这样的通知:

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

查看 THIS 示例项目以获取更多信息。

希望对您有所帮助。

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

self.tableView.reloadData()