How to reload data in a TableView from a different ViewController in Swift

拟墨画扇 提交于 2019-11-26 05:37:02

问题


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

    (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:

    (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!


回答1:


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


来源:https://stackoverflow.com/questions/30541010/how-to-reload-data-in-a-tableview-from-a-different-viewcontroller-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!