我想在前台返回时调用reloadData
的TableView
方法。我的TableView
是以编程方式生成的。
在FirstViewController
中,我有填充TableView
的方法和调用reloadListOfApps
方法的函数reloadData
。
class FirstViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, MFMailComposeViewControllerDelegate {
@IBOutlet weak var listOfApps: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
listOfApps.delegate = self
listOfApps.dataSource = self
}
func reloadListOfApps() {
listOfApps.reloadData()
}
// ================ TABLE DELEGATE/MANAGER ===================
let apps = ListAppClass.listApp()
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return apps!.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
let bundle = apps! [indexPath.row]
let bundle_temp = String(describing: bundle)
cell.textLabel?.text = bundle_temp
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Current Cell!")
}
}
我已经
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
FirstViewController().reloadListOfApps()
}
运行应用程序时出现此错误
致命错误:在展开可选值时意外找到nil
阅读some questions我也检查了故事板中的插座,看起来一切正常。
AppDelegate
对应于Hooks
错误在哪里?
最佳答案
尝试在视图控制器中添加oberver
NotificationCenter.default.addObserver(self,
selector: #selector(applicationWillEnterForeground),
name: .UIApplicationWillEnterForeground,
object: nil)
回拨
@objc func applicationWillEnterForeground() {
listOfApps.reloadData()
}
////解释问题
在AppDelegate中编写此代码时
FirstViewController().reloadListOfApps()
这将动态创建一个实例,该实例的所有属性都为nil,因为您没有加载与当前活动对象相关联的storybaord对象或Xib文件,控件转到reloadListOfApps函数,并发现要重新加载的listOfApps为nil,因此发生崩溃,上面的解决方案是一种方式,另一种方式使用委托或使listOfApps成为可在任何地方引用的共享对象
关于ios - Swift-在前台输入reloadData UITableView,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48408494/