[英]How to reload data in a TableView from a different ViewController in Swift
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. 其中tableViewController是TableView控制器中的类(我知道这不是大写字母),而table是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. 好吧,这样做会产生“致命错误:在展开可选值时意外发现nil”,并且我想这是有道理的,因为尚未加载“ presentedViewController”。 I also tried this: 我也试过这个:
(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). 这产生了相同的结果(我确保tableViewController在navigationController堆栈上的当前ViewController下)。 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 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()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.