gpt4 book ai didi

ios - Swift - reloadData UITableView 进入前台

转载 作者:行者123 更新时间:2023-11-28 10:46:17 24 4
gpt4 key购买 nike

当我在前台返回时,我想调用 TableViewreloadData 方法。我的 TableView 是以编程方式构建的。

FirstViewController 中,我有填充 TableView 的方法和我调用 reloadData 的函数 reloadListOfApps方法。

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!")

}
}

AppDelegate 我已经

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

当我运行应用程序时出现此错误

Fatal error: Unexpectedly found nil while unwrapping an Optional value

阅读 some questions 我也检查了 Storyboard 中的 Outlets,似乎一切正常。

Hooks对应FirstViewController

哪里出错了?

最佳答案

尝试在你的 View Controller 中添加观察者

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,所以发生崩溃,上面的解决方案是一种方法,另一种方法是使用委托(delegate)或使 listOfApps 成为共享对象可以在任何地方引用

关于ios - Swift - reloadData UITableView 进入前台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48408494/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com