如何在 Swift 中从不同的 ViewController 重新加载 TableView 中的数据 [英] How to reload data in a TableView from a different ViewController in Swift

查看:31
本文介绍了如何在 Swift 中从不同的 ViewController 重新加载 TableView 中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个 ViewController 中,我试图像这样在另一个 ViewController 的 TableView 中重新加载数据:

In a ViewController, I'm trying to reload data in a TableView in another ViewController like so:

    (self.presentedViewController as! tableViewController).table.reloadData()

其中 tableViewController 是 TableView 控制器中的类(我知道它不是大写的骆驼),table 是 TableView.好吧,这样做会产生致命错误:在解开可选值时意外发现 nil",我想这是有道理的,因为presentedViewController"尚未加载.我也试过这个:

Where tableViewController is the class in the TableView's controller (It's not upper camel case, I know) and table is the TableView. Well, doing this yields "fatal error: unexpectedly found nil while unwrapping an Optional value" and I guess that makes sense since the "presentedViewController" hasn't been loaded yet. I also tried this:

    (self.navigationController!.viewControllers[self.navigationController!.viewControllers.count - 2] as! tableViewController).table.reloadData()

产生了相同的结果(我确保 tableViewController 在导航控制器堆栈上的当前 ViewController 下).我对我应该做什么感到困惑......我觉得在不同的视图控制器中引用属性应该更容易.我可能有点含糊;如果是,请告诉我您需要知道什么!

which yielded the same result (I made sure the tableViewController was under the current ViewController on the navigationController stack). I'm baffled about what I should do...I feel like it should be easier to refer to properties in different view controllers. I may be a little vague; if I am, tell me what you need to know!

推荐答案

Xcode 9 • Swift 4

创建通知名称:

extension Notification.Name {
    static let reload = Notification.Name("reload")
}

您可以发布通知

NotificationCenter.default.post(name: .reload, object: nil)

并在要重新加载数据的视图控制器上添加一个观察者:

And add an observer at the view controller that you want to reload the data:

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(reloadTableData), name: .reload, object: nil)
}

@objc func reloadTableData(_ notification: Notification) {
    tableView.reloadData()
}

这篇关于如何在 Swift 中从不同的 ViewController 重新加载 TableView 中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆