避免重新加载 UITableView 数据



我有一个问题,即表格显示一长串练习,当用户导航离开然后返回时,我希望将其保留在当前滚动位置。

在我的视图控制器中,我有代码,每当视图出现时,我都会通过调用getDrillList(optimize: true)来加载 UITableView 的数据,该 将数据存储在名为drillListArray的属性中。

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
getDrillList(optimize: true)
}

这是加载数据的代码

private func getDrillList(optimize: Bool = false)
{
// MAKE API CALL, THE ARRAY IS POPULATED IN THE COMPLETE HANDLER
let appDelegate = UIApplication.shared.delegate as! AppDelegate
SharedNetworkConnection.apiGetDrillList(apiToken: appDelegate.apiToken, limit: (optimize ? 13 : 0), completionHandler: { data, response, error in
guard let data = data, error == nil else {                                                 // check for fundamental networking error
print("error=(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
// 403 on no token
print("statusCode should be 200, but is (httpStatus.statusCode)")
print("response = (response)")
SharedNetworkConnection.apiLoginWithStoredCredentials(completionHandler: { data, response, error in
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let json = try? JSONSerialization.jsonObject(with: data!, options: [])
if let dictionary = json as? [String: Any] {
if let apiToken = dictionary["token"] as? (String) {
appDelegate.apiToken = apiToken
self.getDrillList()
}
}
})
return
}
self.drillListParser = DrillListParser(jsonString: String(data: data, encoding: .utf8)!)
self.drillListArray = (self.drillListParser?.getDrillListArray())!
DispatchQueue.main.async {
self.drillTableView.reloadData()
}
if optimize {
self.getDrillList()
}
})
}

两个问题

首先,如果用户被显示到另一个视图控制器的 segue,然后通过Back返回,如何检查数据是否已加载以避免再次加载?检查数组是否为空是否安全?

其次,这种方法有什么我应该注意的吗?

viewDidLoad()中添加getDrillList(optimize: true),它将在生命周期中调用一次,或者您可以检查是否已通过布尔标志检查是否已加载数据。

最新更新