如何从Swift中的另一个ViewController重新加载TableView中的数据

时间:2021-10-05 15:44:50

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

在ViewController中,我试图在另一个ViewController中的TableView中重新加载数据,如下所示:

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

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:

其中tableViewController是TableView控件中的类(我知道它不是上层驼峰的情况),而table是TableView。好吧,这样做会产生“致命的错误:在解开一个Optional值时意外地发现nil”,我想这是有道理的,因为“presentViewController”还没有被加载。我也试过这个:

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

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!

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

1 个解决方案

#1


37  

Xcode 9 • Swift 4

Xcode 9•Swift 4

Create a Notification Name:

创建通知名称:

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

You can post a notification

您可以发布通知

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

#1


37  

Xcode 9 • Swift 4

Xcode 9•Swift 4

Create a Notification Name:

创建通知名称:

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

You can post a notification

您可以发布通知

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