问题描述
在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。好吧,这样做会产生致命的错误:在解开一个Optional值时意外地发现nil,我想这是有道理的,因为presentViewController还没有被加载。
我也试过这个:
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位于navigationController堆栈上的当前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中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!